Juan Jo Murillo
Juan Jo Murillo

Reputation: 11

cosine function in c++ without any math function

I am working on a code to calculate the cosine of a decimal number (in radians). The problem is that I can only get the correct answer when I put a small number. It uses the Taylor series.

double coseno(float x)
{
    double t = x;
    double cos= t;
    for ( int a=1; a<20.0; ++a)
    {
        double mult = -x*x/((2*a)*(2*a-1));
        t *= mult;
        cos += t;
    }
    return cos;
}

Upvotes: 1

Views: 985

Answers (2)

domino_pl
domino_pl

Reputation: 303

  1. You made a mistake. At start you should set t as 1(not x);
  2. You forgot about term. If number is too big or small you could simply use some whiles.
    Eventually it works perfectly:
#include <math.h> //for M_PI
double coseno(float x){
    while(x<0) x+=2*M_PI;
    while(x>2*M_PI) x-=2*M_PI;
    double t = 1;
    double cos= t;
    for ( int a=1; a<40; ++a)
    {
        double mult = -x*x/((2*a)*(2*a-1));
        t *= mult;
        cos += t;
    }
    return cos;
}

Upvotes: 1

Mellgood
Mellgood

Reputation: 325

I think the problem is when you divide using / the operation is not evaluated with the precision you need. When you use small values the approximation is enough to get the correct result but when you use bigger values you get into an approximation problem.

You repeat the approximation error many times inside the for loop and so you get wronger result as the input increases

Upvotes: 0

Related Questions