0% found this document useful (0 votes)
13 views

ACMS 20220 Homework 5

The document outlines the requirements for ACMS 20220 Assignment 5, due on April 12, which includes submitting Python scripts for various programming problems. The problems involve implementing functions for complex number operations, prime factorization, user input handling, file reading and writing, matrix operations, and anomaly detection. Each problem has specific input/output requirements and error handling guidelines, with detailed examples provided for clarity.

Uploaded by

bobbleheads56
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

ACMS 20220 Homework 5

The document outlines the requirements for ACMS 20220 Assignment 5, due on April 12, which includes submitting Python scripts for various programming problems. The problems involve implementing functions for complex number operations, prime factorization, user input handling, file reading and writing, matrix operations, and anomaly detection. Each problem has specific input/output requirements and error handling guidelines, with detailed examples provided for clarity.

Uploaded by

bobbleheads56
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

ACMS 20220 Assignment 5

Due: Wednesday, April 12

Submit your Python scripts for the problems below using Canvas. Make certain to save your scripts
as .py files.

Use the following naming scheme for submitting your solutions on Canvas: For exercise n
on homework m, the name of your submission should be hwmexn.py. As an example, for homework
1 exercise 3, the name of your submission should be: hw1ex3.py. If you do not adhere to this naming
scheme, you may lose some credit.

You may assume that the user always enters a reasonable value when requested (e.g. if the problem
states that the user is to enter a non-negative integer, you may assume that the user enters
something interpretable as a non-negative integer).

1. Write a function named complex nth roots that accepts a numeric value z (int, float, or
complex) and a positive integer n as inputs, and returns the set of all complex nth roots of z. If
the user supplies a value for z not of those types, raise a TypeError with the argument “z must
be complex”. If the user supplies a non-integer value for n, raise a TypeError with the
argument “n must be an int”, or if the user supplies a non-positive value for n, raise a
ValueError with the argument “n must be positive”.
The nth roots of a complex number z are the values:

n o
z 1/n = r1/n eiθ/n+2πik/n k = 0, . . . , n − 1

where r and θ are computed from the polar representation of z. (You can obtain θ using the
phase function in the cmath module.)
2. Let n > 1 be a positive integer, and assume n has the prime factorization:

n = 2α pe11 · · · pemm q1f1 · · · qnfn

where the pi are primes of the form 4k + 1 for k ∈ Z and the qj are primes of the form 4k + 3
for k ∈ Z and all of the exponents are non-negative integers. A fact from number theory asserts
that the number of ways to write n as a sum of two integer squares (distinguishing signs and
order) is given by:

(
0, if any fi is odd
r(n) = Qm
4 i=1 (1 + ei ), if all fi are even

Write a function named r that accepts a dictionary representing the prime factorization of a
positive integer n > 1 and returns the number of ways that n may be written as a sum of
integer squares. Each key in the dictionary will be a distinct prime factor of n, and the
corresponding value will be the power to which that prime factor appears in the prime
factorization.
For example, for the integer n = 45090045000, the prime factorization is given by
(23 )(32 )(54 )(72 )(112 )(132 ). The dictionary passed in for this n would be
{2 : 3, 3 : 2, 5 : 4, 7 : 2, 11 : 2, 13 : 2}. The primes of the form 4k + 3 in this factorization are 3, 7
and 11, and all of these appear to an even power, so r(n) is non-zero. We compute r(n) using
the exponents of the primes 5 and 13 of the form 4k + 1 as: r(n) = 4 ∗ (4 + 1) ∗ (2 + 1) = 60 (so
there are 60 ways of writing 45090045000 as the sum of two integer squares).
As another example, consider the integer n = 20037600, the prime factorization is given by
(25 )(32 )(52 )(112 )(231 ). The dictionary passed in for this n would be
{2 : 5, 3 : 2, 5 : 2, 11 : 2, 23 : 1}. The primes of the form 4k + 3 in this factorization are 3, 11 and
23. 23 appears to an odd power, so it is not possible to write n as the sum of two integer
squares, and hence r(n) = 0 for this value of n (so it is impossible to write 20037600 as the sum
of two integer squares).
3. Write a program that repeatedly prompts the user to enter floating point values (until the user
enters “endinput”). Any other input that is not interpretable as a floating point number is
ignored. The program calculates and reports the count, sum, average, max, and min of all
values interpretable as floating pointing numbers entered in this fashion (when these quantities
are defined).
4. Write a Python script that opens a file named “hw5ex4 input.txt”. Each line of the file will
consist of integers, separated by semicolons. The number of integers per line will vary. The
program computes the sum of each line, and writes the totals (in order) to an output file
named “hw5ex4 output.txt”, with one total per line. See the appropriate folder for a sample of
what the input and output might look like.
5. Write a program implementing Newton’s method for finding the real root of the function
f (x) = x5 − 80x + 160. (See the last page of this assignment for the details of Newton’s
method.) The program reads three values from a file named: “hw5ex5 input.txt”: a starting
value, an error tolerance, and a maximum number of iterations.

In your code, account for the possibility that the derivative of the function will be zero at xi
and terminate the procedure early if this occurs. (You should still write output in this case.)

Implement the function f (x) and its derivative f 0 (x) = 5x4 − 80 as appropriately named
functions in your code.

Write the initial guess and each successive iteration into an output file named
“hw5ex5 output.txt”, with one float per line. Use 16 digits beyond the decimal point for the
output.

Sample output has been provided corresponding to several input files.


6. Write a program that repeatedly prompts the user to enter file names (stopping with an input
of “endinput”). The program then counts the frequency of each letter in the English alphabet
(A through Z) appearing among all the files. Ignore all characters that are not part of the basic
English alphabet. You should count both the upper and lower case form of each letter as the
same entity. Report the count of each letter, along with its overall frequency (as a percentage
of total letters) to the user. You do not have to worry about letters with diacritical marks (e.g.
umlauts) or other variants from the standard alphabet.
7. Write a program that reads from a file named “hw5ex7 input.txt”. The program then reads
two matrices (whose entries are integers) from the file, with both matrices guaranteed to be of
the same dimensions (although the number of rows might be different from the number of
columns). The matrices will be separated from each other in the file by a blank line. The
entries in each row of the matrix will be separated by a blank space, with no characters other
than spaces and those forming the integers appearing on each separate line. The program then
outputs the sum of the two matrices to a file named “hw5ex6 output.txt”, with each row of the
matrix on a separate line in the file, and the entries of each row in the matrix separated by a
space. (Remember that addition of matrices is defined by adding corresponding elements.)

See the appropriate folder for a sample of what the input might look like.
8. In this problem, we will compute real numbers from their (truncated) continued fraction
expansions. A file named “hw5ex8 input.txt” will contain the expansions, with one per line,
which consist of an integer, followed by a semicolon, followed by additional integers, separated
by commas. Your program should process this file, compute the continued fraction expansions
of each line, and write them to an output file named “hw5ex8 output.txt” with 16 digits of
precision beyond the decimal point.
The continued fraction approximation corresponding to

a0 ; a1 , a2 , a3 , . . . , an

is the quantity:

1
a0 +
1
a1 +
1
a2 +
1
a3 +
1
··· + 1
an−1 + an

See the appropriate directory for an example of what the input and corresponding output
might look like.
(Challenge, not due for submission: write both an iterative and recursive function for
performing the computation of the real number from the continued fraction expansion.)
9. The Lychrel function L10 for base 10 is the function that takes a non-negative integer written
in base 10 and adds to that integer the integer formed from reversing its digits. For example,
L10 (37) = 37 + 73 = 110. For some integers n, L10 (n) yields a base-10 palindrome (a number
equal to its reversal in base-10). For example, L10 (132) = 132 + 231 = 363 is a palindrome. For
the purposes of this problem, we will call such a number a one-step palindrome.
Write a Python script that reads from a file named “hw5ex9 input.txt”. The file consists of
non-negative integers, with one integer per line. Write the following information about the
numbers in the file to a file named “hw5ex9 output.txt”:

ˆ The number of one-step palindromes, allowing repeats to count multiple times.


ˆ The sum of all one-step palindromes, allowing repeats to count multiple times.
ˆ The number of distinct one-step palindromes.
ˆ The sum of all distinct one-step palindromes.
10. In this problem, we will detect suspected anomalies in a list of data using the mean and
standard deviation. Let T be a tolerance. For a data set (with at least two observations of a
single variable), we will consider a number a lower anomaly if it is less than T multiples of the
sample standard deviation from the sample mean of the data, and we will consider a number
an upper anomaly if it is greater than T multiples of the sample standard deviation from the
sample mean of the data.
Write a Python script that reads from a file named “hw5ex10 input.txt”. The first line of the
file contains the floating point value T . The second line of the file will be blank. The remaining
lines of the file will consist of the data to be analyzed for anomalies, with one floating point
entry per line. The program then writes to two output files: “hw5ex10 lower anomalies.txt”
and “hw5ex10 upper anomalies.txt”. Each output file will contain the lower and upper
anomalies respectively, in sorted order from least to greatest, with one entry per line.
Note that it is possible that one or more of the output files may be blank (depending on
whether or not there are lower or upper anomalies detected).
Newton’s Method

Newton’s method is a procedure for finding a root of a function f (x) (i.e. to find a value x∗
such that f (x∗ ) = 0).
The method begins with an initial guess x0 for a root of the function. It then constructs an
iterative sequence of approximations based on the formula: xi+1 = xi − ff0(x i)
(xi ) .
This procedure might terminate early if f 0 (xi ) is 0 for some i. Otherwise, it may produce an
exact root (in which case there is no need to continue the procedure), a sequence of
approximations converging to a root, or a divergent sequence of xi values.
In practice, the procedure is run for a maximum number of iterations, or until a stopping
condition is reached (or until the derivative becomes zero). The stopping condition might take
the error condition form: stop once |f (xi )| < , where  is an error tolerance. (There are other
stopping conditions which are often better in practice, though.)
Below is an example of using Newton’s method to approximate the square root of 2 by finding
a root of f (x) = x2 − 2, using an initial guess of 1 and an error tolerance of .000001. (The
equals signs below are only approximate due to rounding.)
x0 = 1
f (x0 ) 12 −2
x1 = x0 − f 0 (x0 ) =1−
(2)(1) = 1.5
f (x1 ) 1.52 −2
x2 = x1 − = 1.5
f 0 (x1 ) − (2)(1.5) = 1.416666666666667
x3 = 1.41421568627451
x4 = 1.41421356237469 (the procedure stops here because |f (1.41421356237469)| < .000001).
Practice Problems:

The following problems are not due for submission. These problems deal with using the built-in
features of the language to handle common linear algebra tasks. You are encouraged to look up the
algorithms and provide your own implementations. Later in the semester, we will encounter the
numpy and scipy libraries, which have data types and functions for performing such linear algebra
tasks in a more convenient and efficient fashion.

ˆ Write a script to read two matrices from a file. The matrices will be formatted to consist of
floating point values, separated by commas. A single blank line will indicate the division point
between the matrices. The matrices may have different dimensions from one another. If the
matrices have compatible dimensions, compute their product using a function written to
perform matrix multiplication (and if not, raise an appropriate exception).

ˆ Write a function to compute Ak , where A is a square matrix and k is a non-negative integer,


using the following observation about exponentiation to improve efficiency.
For k even, xk = (x2 )k/2 . For k odd, xk = x ∗ (x2 )(k−1)/2 .
As an application of this, compute xn , the index n Fibonacci number, by expressing xn and
xn−1 as a certain matrix to a power times the vector (x1 , x0 ).

ˆ Write a function to solve the matrix-vector equation Ax = b, where A is an n × n matrix, and


x and b are vectors in Rn , using Gaussian elimination to solve the system. Raise an exception
if the matrix is not invertible.

ˆ Write a function that accepts an iterable of k vectors (represented as lists), each assumed to
have n ≥ k components. The function performs the modified Gram-Schmidt procedure to
generate an orthonormal basis for the span of those vectors. Raise an exception if the original
vectors were linearly dependent.

You might also like