Homework 2

Student's Name: PLEASE INSERT YOUR NAME HERE (DOUBLE CLICK THIS BOX TO EDIT.)

Directions: Add work to this notebook to solve the problems below.

Check your work. I give some tests that should be passed if you get it correct.

Problem Sources:

  • LL: Programming for Computations - Python by Svein Linge and Hans Petter Langtangen, 2nd edition.
  • L: A Primer on Scientific Programming with Python by Hans Petter Langtangen, 2nd edition.
  • TAK: Applied Scientific Computing With Python by Peter R. Turner, Thomas Arildsen, and Kathleen Kavanagh.

1. A for Loop with Errors

Below, a program has been written for the task of adding all integers $i =1, 2,\ldots ,10$ and printing the final result. Fix the program.

(This is Exercise 3.1 from LL.)

In [ ]:
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sum = Sum + x
print sum: , sum

2. The range Function

Write a slightly different version of the program above. Now, the range function should be used in the for loop header, and only the even numbers from [2, 10] should be added. Also, the (only) statement within the loop should read sum = sum + i.

(This is Exercise 3.2 from LL)

In [ ]:
 

3. Area of Rectangle Versus Circle

Consider one circle and one rectangle. The circle has a radius $r = 10.6$. The rectangle has sides $a$ and $b$, but only $a$ is known from the outset. Let $a = 1.3$ and write a program that uses a while loop to find the largest possible integer $b$ that gives a rectangle area smaller than, but as close as possible to, the area of the circle. Run the program and confirm that it gives the right answer (which is $b = 271$).

(This is Exercise 3.6 from LL.)

In [ ]:
 

4. Frequency of Random Numbers

Write a function named dice that takes a positive integer $N$ as input and then draws $N$ random integers from the interval $[1, 6]$. In the function, count how many of the numbers, $M$, that equal $6$ and print out the fraction $M/N$. Also, print all the random numbers to the screen so that you can check for yourself that the counting is correct. Run the program with a small value for $N$ (e.g., $N = 10$) to confirm that it works as intended.

Hint: After running import random a random integer $x$ in $[1, 6]$ can be generated by x = random.randint(1,6).

(This is Exercise 3.7 from LL)

In [ ]:
 

5. Evaluating a series

Write a computer program to “sum” the series $$\sum_{k=1}^\infty \frac{1}{2^k-1} = \frac{1}{2-1} + \frac{1}{4-1} + \frac{1}{8-1} + \ldots$$ stopping when

  • all subsequent terms are zero to four decimal places, and
  • two successive “sums” are equal to five decimal places. Store the result in the variable series_sum.

(Hints: Use Python floats. The number $x$ is zero to four decimal places if $x < 0.5 \cdot 10^{-4}$. The numbers $x$ and $y$ are equal to five decimal places if $|x-y|<0.5 \cdot 10^{-5}$.)

This problem is based on problem 4 from chapter 2 of TAK.

In [ ]:
 

The following test should be satisfied by your answer. You will know if the test is passed if no error is printed.

In [ ]:
assert type(series_sum) == float, "Error: 'series_sum' should be a float."

6. Ternary to int

Write a function named ternary_to_int which takes as input a string consisting only of elements of $\{0,1,2\}$ giving the ternary expansion of a positive number and produces the integer.

Hints:

  • You can tell the number of characters in a string s with the command len(s).
  • You can get the $k$-th character with s[k]. A trick to get the $j$-th character from the end is to type s[-j]. In particular the first character is always s[0] and the last character is always s[-1].
  • You can convert a string s to an integer using int(s). This works for single characters for instance.
  • You can get the substring of s not including the first character using s[1:] and the substring not including the last character using s[:-1]. These are examples of string slices, which are covered in the Python tutorial and in LL § 2.3.5. (The notion of slices works for strings, numpy arrays, lists and tuples.)
In [ ]:
 

Testing: To test that your program works as expected, I copyied in the ternary function from the Number Representations notebook. This function converts an integer $n$ into a ternary string. Your function should satisfy ternary_to_int(ternary(n))==n for every positive integer n.

The following loop carries this test out for the first $n=1$ to $100$.

In [ ]:
def ternary(n):
    # Below we peform sanity checks on the input.
    assert type(n) == int, 'n must be an integer'
    assert n>0, 'n must be a positive integer.'

    rep = '' # This will store the ternary representation.
    while n != 0:
        trit = n % 3
        rep = str(trit) + rep # add the new trit on the left.
        n = n // 3 # Update the value of n.
    return rep

for n in range(1,101):
    tern = ternary(n)
    out = ternary_to_int(tern)
    assert out == n, ("Error: Output of `ternary_to_int('{}')` " + \
        "should be {}, but was {}.").format(tern, n, out)

7. Exact comparisons

Let $r=\sqrt[5]{2}$ be the $5$-th root of $2$. Write a function compare_to_fraction(p,q) which returns True if $r < \frac{p}{q}$ and returns False if $r > \frac{p}{q}$.

You should use the interval arithmetic package in mpmath, and repeatedly increase the precision.

In [ ]:
 

The following assertion tests will be passed by a correct answer (Nothing happening is good!)

In [ ]:
assert compare_to_fraction(309, 269), "Error, 'compare_to_fraction(309, 269)' should return True."
assert not compare_to_fraction(7810, 6799), "Error, 'compare_to_fraction(7810, 6799)' should return False."

8. Computing digits.

Compute the $20$ most significant digits of $\pi^3$. Store the answer as a string in the variable pi_cubed. The last digit should be rounded (and so may not really be the $20$th digit). (Rounding is done automatically by the nstr function.)

Include code that carries out this calculation.

In [ ]:
 

The following tests should be passed:

In [ ]:
assert type(pi_cubed) == str, "Error: pi_cubed should be a string."
assert len(pi_cubed) == 21, "Error: pi_cubed should have 20 significant digits."
# Note that the decimal point means that there will be one more character than