Introduction to Computer Science: The Way of the Program — Homework 2

Due by 11:59pm Tuesday, September 19

Reading


Programming Exercises

Do the following exercises in the order shown. Using IDLE, create a new blank file named assign2.py and put all of your program definitions for this assignment in the file, including your definitions from lab. You are free to use any of the code that we discussed in class as a basis or guide for writing your own programs.

  1. Finish all of your programs from Lab 2 and cut and paste their code definitions into your assign2.py file. Checklist:

  2. Two points in a plane are specified using the coordinates (x1, y1) and (x2, y2). Write a program called distance() that asks the user for the values of x1, y1, x2, and y2 in that order, and reports the distance between the two points using the formula below. You can use the function math.sqrt(n) in the math library to compute the square root of a number n.

    >>> distance()
    Enter x1: -2
    Enter y1: 0
    Enter x2: 1
    Enter y2: 4
    The distance between the points is 5.0
    
  3. It is a well-known fact from trigonometry that if you take any angle θ (expressed in any units) and add the square of its sine to the square of its cosine, you will always get 1. That is: sin(θ)2 + cos(θ)2 = 1. Write a program called trig() to verify this. Your program should ask the user for an angle, and then print out the result of the computation as shown in the examples below. You can use the math.sin and math.cos functions from the math library to calculate the sine and cosine of an angle.

    >>> trig()
    Enter an angle: 20
    sine of 20 is 0.9129452507276277
    cosine of 20 is 0.40808206181339196
    The sum of those values is 1.0
    
    >>> trig()
    Enter an angle: -1
    sine of -1 is -0.8414709848078965
    cosine of -1 is 0.5403023058681398
    The sum of those values is 1.0
    
  4. Imagine that you are counting on a grid that has five columns (numbered 0 through 4), and an infinite number of rows (starting from 0), as shown below. Write a program called grid5() that asks the user for a number and reports the row and column of that number on the grid. Hint: you don't need a loop for this problem, but the integer division (//) and remainder (%) operators will be helpful. For example:

               column #
              0  1  2  3  4
     row # |----------------
        0  |  0  1  2  3  4
        1  |  5  6  7  8  9
        2  | 10 11 12 13 14
        3  | 15 16 17 18 19
        4  | 20 21 22 23 24
        5  | 25 26 27 28 29
        6  | 30 31 32 33 34
        7  | 35 36 37 38 39
        8  | 40 41 42 43 44
          ...
    
    >>> grid5()
    Enter a number: 8
    8 appears at row 1 column 3
    
    >>> grid5()
    Enter a number: 17
    17 appears at row 3 column 2
    
    >>> grid5()
    Enter a number: 99
    99 appears at row 19 column 4
    
  5. Write a program called coins() that asks the user for a total amount of money in cents, and converts this to quarters, dimes, nickels, and pennies. The number of quarters should be the maximum number possible given the input amount, followed by the maximum possible number of dimes from the amount left over, and so on. Hint: use the seconds() program that we wrote in class as a guide. Your output should look like the examples below (for now, don't worry about mismatched plural words like "1 nickels").

    >>> coins()
    Total amount of money in cents? 98
    98 cents is equivalent to
    3 quarters
    2 dimes
    0 nickels
    and 3 pennies
    
    >>> coins()
    Total amount of money in cents? 134
    134 cents is equivalent to
    5 quarters
    0 dimes
    1 nickels
    and 4 pennies
    
  6. Modify the printDigits() program that we developed in class so that it prints the digits in left-to-right order, instead of right-to-left. You are not allowed to convert the number to a string for this problem. Hint: think about how you would break the number 75104 into 7 and 5104 (instead of 7510 and 4) with the // and % operators. You could initialize the placeValue variable to 10000 and then decrease it on each loop cycle. Make sure your program works correctly for numbers of different sizes. Examples:

    >>> printDigits()
    Enter a number: 75104
    That number has 5 digits
    7 is in the 10000 's position
    5 is in the 1000 's position
    1 is in the 100 's position
    0 is in the 10 's position
    4 is in the 1 's position
    
    >>> printDigits()
    Enter a number: 925
    That number has 3 digits
    9 is in the 100 's place
    2 is in the 10 's place
    5 is in the 1 's place
    
  7. The infinite series shown below converges to a particular value as more and more terms are added together. Write a program called converge() that asks the user for the number of terms to add up and then prints the result. What value does this series converge to in the limit, as the number of terms becomes larger and larger? Include your answer in a comment in your code.

  8. We can calculate the value of the trigonometric function sin(x), where x is in radians, by using the infinite series below. (The notation 5! denotes the "factorial" of 5, which equals 1 × 2 × 3 × 4 × 5 = 120.) Write a program called sine() that asks the user for x, followed by the number of terms to add up, and computes an approximation of sin(x) using this series. The program should print out the running total of the series as it goes (not the individual terms), as well as the final value. For comparison, also print out the value computed by math.sin(x). For this problem, you can use the exponentiation operator ** to compute the numerator of each term, and the math library function math.factorial(n) to compute the factorial n! of a number n. Hint: x1 = x, and 1! = 1.

    >>> sine()
    Value of x? 7
    How many terms to add up? 15
    total is 7.0
    total is -50.166666666666664
    total is 89.89166666666668
    total is -73.50972222222222
    total is 37.694000771604934
    total is -11.842203107463526
    total is 3.7172455468592602
    total is 0.08670752751727662
    total is 0.7407382736487369
    total is 0.647032114115282
    total is 0.6579644993941851
    total is 0.6569058296735009
    total is 0.6569922877006901
    total is 0.6569862528811284
    total is 0.6569866170512744
    final approximation is 0.6569866170512744
    math.sin function says 0.6569865987187891
    
  9. We can calculate the value of the trigonometric function cos(x), where x is in radians, by using the infinite series below. Write a program called cosine() that asks the user for x, followed by the number of terms to add up, and computes an approximation of cos(x) using this series. The program should print out the running total of the series as it goes (not the individual terms), as well as the final value. For comparison, also print out the value computed by math.cos(x). For this problem, you can use the exponentiation operator ** to compute the numerator of each term, and the math library function math.factorial(n) to compute the factorial n! of a number n. Hint: x0 = 1, and 0! = 1, by definition.

    >>> cosine()
    Value of x? -1
    How many terms to add up? 10
    total is 1.0
    total is 0.5
    total is 0.5416666666666666
    total is 0.5402777777777777
    total is 0.5403025793650793
    total is 0.540302303791887
    total is 0.5403023058795627
    total is 0.540302305868092
    total is 0.5403023058681398
    total is 0.5403023058681397
    final approximation is 0.5403023058681397
    math.cos function says 0.5403023058681398
    

EXTRA CREDIT PROBLEMS (OPTIONAL):

You should finish the other problems first before working on these.

  1. In order to convey a more intuitive idea of the vastness of cosmic time scales and the relative youth of the human species compared to the age of the Universe, the astronomer Carl Sagan imagined compressing the entire history of the Universe into a single calendar year, beginning with the Big Bang on January 1st and ending with our present epoch on the last second of December 31st. Assuming the Universe to be 13.787 billion years old (the current best estimate), each second of Cosmic Calendar time corresponds to several centuries of real time. Write a program called cosmic() that asks the user for an amount of real time in years and calculates how many calendar-days, -hours, -minutes, and -seconds in the past this corresponds to on the Cosmic Calendar. You should round the seconds to one decimal place. For example, the formation of the Earth occurred about 4.6 billion years ago—around 121 days ago on the Calendar—and humans evolved roughly 2.5 million years ago—just an hour and a half ago on the Calendar:

    >>> cosmic()
    How many years ago? 4600000000
    That was 121 days 18 hours 45 minutes and 11.9 seconds ago on the Cosmic Calendar
    
    >>> cosmic()
    How many years ago? 2500000
    That was 0 days 1 hours 35 minutes and 18.4 seconds ago on the Cosmic Calendar
    

    Agriculture was invented roughly 15,000 years ago, the dinosaurs were wiped out 66 million years ago, and the largest mass extinction in Earth's history—the Permian-Triassic event, in which over 90% of marine life and 70% of terrestrial life was wiped out—occurred 251 million years ago. How long ago did these events take place on the Cosmic Calendar?

  2. How much hair do you have on your head? Let's write a program to find out! For this problem we'll use the following facts: there are 2.54 centimeters in an inch, 12 inches in a foot, 5280 feet in a mile, the circumference of a circle is 2 π r, and the surface area of a sphere is 4 π r2. For the purposes of estimation, let's assume that your head is a perfect sphere and exactly half of it is covered by hair. A rough measurement with a ruler reveals about 15 hairs per centimeter on a typical scalp, or about 38.1 hairs per inch (15 × 2.54). Thus there are about 38.12 hairs per square inch of scalp, which is about 1450 hairs per square inch. Using these assumptions, write a program called hair() that asks you for the circumference of your head in inches, and the average length of a strand of your hair in inches. It then estimates the total length of all of your hair in miles, rounded to one decimal place. Hint: use the circumference to compute the total area of your scalp (the top half of your head) in square inches. From this you can calculate the total number of individual hairs on your head. Then figure out the total length of hair in inches, and finally convert this to miles. For example:

    >>> hair()
    Circumference of your head in inches? 23
    Average length of a strand of your hair in inches? 0.75
    You have about 1.4 miles of hair on your head!
    
    >>> hair()
    Circumference of your head in inches? 22
    Average length of a strand of your hair in inches? 9
    You have about 15.9 miles of hair on your head!
    
  3. Write a new version of your sine program from Exercise 8 called sine2() that gives the same output as the original version, but without using the exponentiation operator ** or the math library functions math.pow or math.factorial. Instead, keep track of the numerator in a separate variable numer, and update the denominator variable denom by keeping track of two separate multiplicative factors factor1 and factor2 as you go through the loop.

  4. Write a new version of your cosine program from Exercise 9 called cosine2() that gives the same output as the original version, but without using the exponentiation operator ** or the math library functions math.pow or math.factorial. Instead, keep track of the numerator in a separate variable numer, and update the denominator variable denom by keeping track of two separate multiplicative factors factor1 and factor2 as you go through the loop.


Turning in Your Homework