This week's giveaway is in the Java/Jakarta EE forum. We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line! See To calculate sin(x), you must use a loop to calculate the sum above for the first 30 terms. Again, progressively compute each term."
For the e^x calculation I am pretty on point, but for the sin(x) statement i am not sure on where my calculation went wrong. Any helps would be greatly appreciated. Thank you
If those are only rounding errors, simply print the output with fewer places after the decimal point
Why are you returning double from your factorial method? Factorials are defined as integers and they take non negative integer arguments. You will get overflow for ints at 13! and for longs at 22! (I think), so try this instead. The last time I tried that for factorils, I got a stack space exception about 5000! but don't worry. You will get double overflow and return ∞ long before that.
I've got a couple of suggestions. First, keep in mind that the Taylor series as you've coded it converges fast when x is close to zero but more slowly as x moves away from zero. It is possible to expand the series around other constants, but I don't think you need to look at that for this assignment... maybe for a class in Calc, but not for this assignment :-)
Anyway, when I'm working with series summations and want to get all the accuracy I possibly can, I find that it is often better to add up the terms from smallest magnitude to largest. If you start with the largest, then the running sum gets so large that there just isn't enough precision to capture the contribution of the small order terms. Imagine a case where you have nine terms. If you add up the 6 largest, the three smallest might be so small that when you add them they don't even change the sum. But if you took the three smallest together, added them up first, and then added that to the others, they might be big enough to significantly affect the sum.
That being said, a little algebra can solve a lot of your issues. Consider the following snippet of code. It adds up the terms from smallest to largest, and so preserves the small-order contribution It avoids having to compute the values for factorial (which can get enormous very quickly). And it even runs pretty fast.
For your homework assignment, you would probably want to code this logic into a loop rather than using explicit terms as I did. As the saying goes, the results are "left as an exercise for the student."
a fool thinks himself to be wise, but a wise man knows himself to be a fool - shakespeare. foolish tiny ad: