Easy question from a really new guy
Hi guys, I am really new to programming and I am reading "How to Think Like a Computer Scientist" in order to learn. I really like the book. Anyway, I have been doing all the exercises and I have become stumped. Here is my problem:
Changing
total = total + Math.pow(x,i)/factorial(i);
to
total = total + total*(x/i);
Yields an entirely different result.
Prolbem set B: You can make this method much more efficient if you realize that in each iter-
ation 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 use of Math.pow and factorial, and check that
you still get the same result.
Whole program:
public static double myExp(double x){
double i = 1;
double total = 1;
while(i < 555){
total = total + (total*(x/i);
i++;
}
return total;
}
public static double factorial(double x){
double i = x;
double total = 1;
while(i > 1){
total = i*total;
i--;
}
return total;
}
Re: Easy question from a really new guy
Here is the original problem if it helps at all?
One way to calculate e^x is to use the infinite series expansion
e^x = 1 + x + x2/2! + x3/3! + x4/4! + ... (6.3)
If the loop variable is named i, then the ith term is equal to xi/i!.
a. Write a method called myexp that adds up the first n terms of the series shown
above. You can use the factorial method from Section 5.10 or your iterative
version.
b. You can make this method much more efficient if you realize that in each iter-
ation 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 use of Math.pow and factorial, and check that
you still get the same result.
Re: Easy question from a really new guy
I got it figured out! Thanks for all those who took a look and tried to help!