Search code examples
c++trigonometrytaylor-series

In C++ finding sinx value with Taylor's Series


I am trying to write a block of codes in C++ that calculates sinX value with Taylor's series.

#include <iostream>
using namespace std;
// exp example
#include <cstdio>      // printf
#include <cmath>       //  exp

double toRadians(double angdeg)         //convert to radians to degree
{                                       //x is in radians
    const double PI = 3.14159265358979323846;
    return angdeg / 180.0 * PI;
}

double fact(double x)       //factorial function 
{                           //Simply calculates factorial for denominator
    if(x==0 || x==1)
        return 1;
    else
        x * fact(x - 1);
}

double mySin(double x)      //mySin function
{
    double sum = 0.0;
    for(int i = 0; i < 9; i++)
    {
        double top = pow(-1, i) * pow(x, 2 * i + 1);  //calculation for nominator
        double bottom = fact(2 * i + 1);              //calculation for denominator
        sum = sum + top / bottom;                     //1 - x^2/2! + x^4/4! - x^6/6!
    }
    return sum;
}

int main()
{
    double param = 45, result;

    result = mySin(toRadians(param)); //This is my sin value
    cout << "Here is my homemade sin : " << result << endl;

    result = sin(param);              //This is library value
    cout << "Here is the API sin : " << result << endl;

    return 0;
}

So my program works without any error. My output is exactly:

Here is my homemade sin : nan
Here is the API sin:0.850904

I know I am making a big logic mistake but I couldn't find it out. It is my second week with C++. I am more familiar with Java. I coded the same thing and It worked absolutely perfect. The answers matched each other. Thanks for your time and attention!


Solution

    1. in fact, you miss the return: x*fact(x-1); should be return x*fact(x-1);. You can see the compiler complaining if you turn the warnings on. For example, with GCC, calling g++ -Wall program.cpp gives Warning: control reaches end of non-void function for the factorial function.

    2. The API sin also needs the angle in radians, so change result=sin(param); into result=sin(toRadians(param));. Generally, if in doubt about the API, consult the docs, like here.