We know that
sin(x)=x-x^3/3!+x^5/5!-x^7/7!+x^9/9! and so on. I have written this code:
#include <iostream>
#include <math.h>
using namespace std;
const int m=19;
int factorial(int n) {
if (n==0){ return 1;}
return n*factorial(n-1);
}
int main() {
float x;
cin >> x;
float sum=0;
int k=1;
for (int i=1;i<=m;i+=2) {
sum+=(k*(powf(x,i)/factorial(i)));
k=k*(-1);
}
cout<<"series sum is equal :"<<sum<<endl;
return 0;
}
One problem is that when I enter x=3 it gives me -10.9136, but I know that values range of sin(x) is [-1, 1] what is problem? Please help me.
The problem is that you’re running out of precision due to destructive cancellation.
You have an alternating series where some of the terms get very large. But those terms cancel each other out to a small result. Since
floathas limited precision, your round off error is larger than your final value.You can “reduce” the problem by using double-precision. But it won’t go away. Standard implementations of
sin/cosinvolve taking the modulo of the argument by2 pito make it small.EDIT :
I found the other problem. You have an integer overflow in your factorial function when
i = 19.