I'm currently in a Java class at my university and we've been asked to code a Taylor Series equation to compute a Sine function. I've coded what makes sense to me, and I've tried debugging every section of code I can think of to make sure all of the parts are functioning the way I think they should, but the program still isn't functioning right. So, I'm hoping someone might look at this and spot what I'm doing wrong.
this is the equation: Taylor Series Equation
public class Sine {
public static int factorial(int a) {
int num = a;
if (a == 1) return 1;
for (int i = 1; i < num; i++){
a = a * i;
} return a;
}
public static double numerator(double x, int power) {
double ret = Math.pow(x, power);
return ret;
}
public static void main(String[] args) {
int power = 1;
int iter = 0;
double x = Math.PI/4;
int sign = 1;
while (iter != 10) {
iter++;
System.out.println("Iteration " + iter + ": " + x);
x += sign * numerator(x, power)/factorial(power);
power += 2;
sign *= -1;
}
System.out.println("\nTaylor Series, Final: " + x);
System.out.println("Value of Sine: " + Math.sin(Math.PI/4));
}
}
I'm just very confused what's going on and why it's not working.
What you're doing wrong (thanks @AndyTurner) is trying to store large factorials in an
int
, which of course can only store numbers up to about 2 billion.To avoid having to deal with large numbers and their limited accuracies, you could use the following principle, that applies to the Taylor series for sines.
For example, if you've already calculated x5 / 5!, then the best way to calculate -x7 / 7! is to multiply the number you've already calculated by -x2 / 6 / 7.
If you calculate your terms this way, then add them up, you avoid all the problems that come with dealing with large numbers.