CS 206 -- Assignment 5
Recursion
In this homework you will write 2 recursive programs for doing mathematical calculations. You only have 1 week to do this howework, but it requires relatively little programming.
Cube Roots -- 70% of grade
The nth-root of a number can be computed by repeatedly applying the following formula:
newguess = lastguess - (f(lastguess)-target) / (f'(lastguess)))
until newguess is within some error bound of the correct answer. For example if you want the cube-root
then f(x)=x*x*x and f'(x)=3*x*x. So, if you want the cube-root of 30, and your previous guess was 5.0, then your new guess would be:
newguess = 5 - (5*5*5-30)/(3*5*5)
= 5 - 95/75
= 3.73
Using this formula, write a recursive function to compute the cube root of a number. Your method should return a cube-root that is guaranteed to be accurate to within some error bound. Your method should work on any positive real number (subject to the constraint that it fits within the limitations of a java double.
The function should print a list of the numbers explored along the way to the answer. You can use any positive number as the first guess, I always use 5.0. For instance, here is my output for computing the cube-root of 9999 to within 1.0 of getting back to 9999:
5.0
202.48
101.36194452557547
51.16757741819298
27.493364332375048
20.3607827973357
22.240122676133293
21.22775836672168
21.70864913928902
21.462995387806323
21.58440036391834
21.523358365263825
21.553792559057946
21.538554005791013
21.546167887963065
21.54235960207372
21.544263408342058
You program must satisfy the following constraints:
- It must use recursion
- It must not use for, while or any other form of loop
- The only math operators you may use are *, /, - and +.
- It must accept the precision and number as a command line argument. E.g., to generate the output above my command was
java CubeRoot 1 9999
- You may define precision as you find convenient. For example, it may be easier to define precision in term sof the differnece between lastguess and newguess. I.e., if (lastguess-newguess)<0.01 then stop
Nth Root -- 30% of grade
Take you cube root program and generalize it to compute the Nth root (where N is an integer). This program can not use loops, it can only use recursion.
You program must satisfy the following constraints:
- It must use recursion
- It must not use for, while or any other form of loop
- It must print out its series of estimates.
- The only math operators you may use are *, /, - and +.
- It must accept the precision, number and root as a command line argument. E.g., to compute the 7th root of 1211977 to a tolerance of 4000 (in my case tolerance implies that n^7 is within 4000 of 1211977) my command would be
java NthRoot 4000 7 1211977
and the output would be:
5.0
15.366646857142857
13.184561468313749
11.33401382549392
9.79654488971303
8.592904335694135
7.795433733423169
7.453333568900643
7.398505620334887