Search code examples
c++factorial

Why does it show nan?


Ok so i am doing an a program where I am trying to get the result of the right side to be equivalent to the left side with 0.0001% accuracy
sin x = x - (x^3)/3! + (x^5)/5! + (x^7)/7! +....

#include<iostream>
#include<iomanip>
#include<math.h>

using namespace std;

long int fact(long int n)
{
    if(n == 1 || n == 0)
        return 1;
    else
        return n*fact(n-1);
}

int main()
{
    int n = 1, counts=0; //for sin
    cout << "Enter value for sin" << endl;
    long double x,value,next = 0,accuracy = 0.0001;
    cin >> x;
    value = sin(x);
    do
    {
        if(counts%2 == 0)
            next = next + (pow(x,n)/fact(n));
        else
            next = next - (pow(x,n)/fact(n));
        counts++;
        n = n+2;
    } while((fabs(next - value))> 0);
    cout << "The value of sin " << x << " is " << next << endl;
}


and lets say i enter 45 for x I get the result
The value for sin 45 in nan.


can anyone help me out on where I did wrong ?


Solution

  • First your while condition should be while((fabs(next - value))> accuracy) and fact should return long double. When you change that it still won't work for value of 45. The reason is that this Taylor series converge too slowly for large values. Here is the error term in the formula

    enter image description here

    Here k is the number of iterations a=0 and the function is sin.In order for the condition to become false 45^(k+1)/(k+1)! times some absolute value of sin or cos (depending what the k-th derivative is) (it's between 0 and 1) should be less than 0.0001. Well in this formula for value of 50 the number is still very large (we should expect error of around 1.3*10^18 which means we will do more than 50 iterations for sure). 45^50 and 50! will overflow and then dividing them will give you infinity/infinity=NAN. In your original version fact value doesn't fit in the integer (your value overflows to 0) and then the division over 0 gives you infinity which after subtract of another infinity gives you NAN.