RandomPleb
RandomPleb

Reputation: 424

Why doesn't this code correctly compute sin(x)?

I am about to lose my mind. I have been staring at this for hours, and I cannot figure out what is wrong. When I enter a value of "1", I just get that the sum is 1, meaning that it has only gone this through the iteration once, but I don't know why seeing that the abs(term) should be greater than "lesser".

I am trying to calculate sin(x) given the user inputs x.

double sum = 0.0;
double term = 0.0;
double n = 1.0;
double x = 0.0;
double lesser = 1.0e-15;


while (true)
{
    std::cout << "\nEnter radian value of x:";
    std::cin >> x;
    if (x == 999)
        return 0;

    term = x;
    sum = 0.0;
    n = 1.0;

    while (abs (term) >= lesser)
    {
        sum = sum + term;
        n = n + 1.0;
        term = -term * (x/n);
        n = n + 1.0;
        term = term * (x/n);

    }
    std::cout << "\nApproximation for sin(0) is is: " << sum;
}


return 0;

Upvotes: 1

Views: 274

Answers (2)

templatetypedef
templatetypedef

Reputation: 372664

The std::abs function works on integral types. You probably should be using std::fabs:

while (fabs (term) >= lesser) {
   ...
}

There may be other errors in the code, but this one will probably cause the loop to exit early because abs will round values in the range (0, 1) down to 0. fabs avoids this.

Alternatively, use the <cmath> header instead of the <math.h> header, or explicitly call std::abs. <cmath> exports overloads of abs for floating-point values.

Hope this helps!

Upvotes: 3

cppguy
cppguy

Reputation: 3713

Use fabs, not abs. abs is for integers and is killing the fractional part of your number. Or you can use std::abs

Upvotes: 0

Related Questions