A little help debugging my sin(x) approximation

So I have written a Maclaurin series approx. for sin(x)
and it works for values really close to 0 but for pi it outputs
0.787619 which is no where near sin(pi).
Is the code wrong or is the approximation really suppose to be that off?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  float factorial(int num){
	float fac = num;
	for (int i = num; i > 1; i--){
		fac = fac * (num - 1);
	}
	return fac;
}

void sinxApprox(int choice, float x){

	float approx = 0.0;
	int count = 0;

	for (int n = 0; n <= choice; n++) {
		approx += pow(-1, n) * pow(x, 2 * n + 1) / factorial(2 * n + 1);
		count++;
		if (count % 100 == 0) {
			cout << "After " << count << " terms, the value of sin(x) is " << setprecision(15) << approx << endl;
		}
	}
}


So yeah, that's the factorial and sin approximation functions I wrote where choice is
the amount of terms and x is the value near 0.
It works great for values really close to 0 but that's about it.
Last edited on
Without knowing how big "choice" is, your approximation could be really far off if you aren't doing enough iterations.
sine takes a lot of iterations to get a good approximation.
I did 50000 iterations... and the values were still only accurate to the 0.01 place.
And that was at values of around x = 0.5.

So the code itself is alright?
[(-1)^n/(2n + 1)!] * (x)^(2n+1)

Maybe double check your parenthesis in your function?

Edit: Your code for the mathematics behind it looks fine.

approx += ( (pow(-1, n) * pow(x, 2 * n + 1)) / factorial(2 * n + 1) ) ;

I spaced it out a little so it's easier to see what parts are enclosed in what parenthesis.

No need to do 50000 iterations. a 64-bit integer can only hold 2^64 - 1, which is much much much less than (50000)!. Try using a smaller number of iterations (like 10 or 12).
Factorials blow up faster than anything (incredibly fast). If you use a 32-bit integer, that value is even smaller.

12! is the max for a 32-bit integer, and 20! is the maximum for a 64-bit integer.

If you go over the maximum value for integers, you will get overflow, and it can royally screw up your values afterwards.
Last edited on
Topic archived. No new replies allowed.