next up previous
Next: Captain Crunch Up: Assignment 8: Strings, series, Previous: Assignment 8: Strings, series,

Series from heck

One way to evaluate ex is to use the infinite series expansion


ex = 1 + x + x2 / 2! + x3 / 3! + x4 / 4! + ... (1)

If the loop variable is named i, then the ith term is equal to xi / i!.

1.
Write a method called myexp that adds up the first n terms of the series shown above. You may use the factorial method from the book.

2.
You can make this method much more efficient if you realize that in each iteration the numerator of the term is the same as its predecessor multiplied by x and the denominator is the same as its predecessor multiplied by i. Use this observation to eliminate the calls to Math.pow and factorial, and check that you still get the same result.

3.
Write a method called check that takes a single parameter, x, and that prints the values of x, Math.exp(x) and myexp(x) for various values of x. The output should look something like:

1.0     2.708333333333333       2.718281828459045

HINT: you can use the String "
t"
to print a tab character between columns of a table.

4.
Vary the number of terms in the series (the second argument that check sends to myexp) and see the effect on the accuracy of the result. Adjust this value until the estimated value agrees with the ``correct'' answer when x is 1.

5.
Write a loop in main that invokes check with the values 0.1, 1.0, 10.0, and 100.0. How does the accuracy of the result vary as x varies? Compare the number of digits of agreement rather than the difference between the actual and estimated values.

6.
Add a loop in main that checks myexp with the values -0.1, -1.0, -10.0, and -100.0. Comment on the accuracy.


next up previous
Next: Captain Crunch Up: Assignment 8: Strings, series, Previous: Assignment 8: Strings, series,
Allen B. Downey
1999-10-25