user2063355
user2063355

Reputation: 3

Problems with cout ( C++)

I am having the hardest time figuring out what is wrong here:

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

double fact(double);
double sinTaylor(double);
double cosTaylor(double);

int main()
{
    double number, sineOfnumber, cosineOfnumber;

    cout << "Enter a number, then I will calculate the sine and cosine of this number" << endl;

    cin >> number;

    sineOfnumber = sinTaylor(number);
    cosineOfnumber = cosTaylor(number);

    cout << fixed << endl;
    cout << cosineOfnumber << endl;
    cout << sineOfnumber << endl;

    return 0;
}

double fact(double n)
{
    double product = 1;
    while(n > 1)
     product *= n--;
    return product;
}

double sinTaylor(double x)
{
    double currentIteration, sumSine;

    for(double n = 0; n < 5; n++)
    {
        currentIteration = pow(-1, n)*pow(x, 2*n+1) / fact(2*n+1);
        sumSine += currentIteration;
    }
    return sumSine;
}

double cosTaylor(double y)
{
    double currentIteration, sumCosine;

    for(double n = 0; n < 5; n++)
    {
        double currentIteration = pow(-1, n)*pow(y, 2*n) / fact(2*n);
        sumCosine += currentIteration;
    }
    return sumCosine;
}

Ok, so here's my code. I'm pretty content with it. Except for one thing: sineOfnumber and cosOfnumber, after the calling of sinTaylor and cosTaylor, will add each other in the following cout line that will print each other. In other words, if number is equal to lets say, .7853, 1.14 will be printed in the line that is intended to print cosineOfnumber, and sineOfnumber will print the result normally. Can anyone help me identify why this is? Thank you so much!

Upvotes: 0

Views: 1070

Answers (2)

vonbrand
vonbrand

Reputation: 11831

The series for the sine is (sorry for the LaTeX):

sin(x) = \sum_{n \ge 0} \frac{x^{2 n + 1}}{(2 n + 1)!}

If you look, given term t_{2 n + 1} you can compute term t_{2 n + 3} as

t_{2 n + 3} = t_{2 n + 1} * \frac{x^2}{(2 n + 2)(2 n + 3)}

So, given a term you can compute the next one easily. If you look at the series for the cosine, it is similar. The resulting program is more efficient (no recomputing factorials) and might be more precise. When adding up floating point numbers, it is more precise to add them from smallest to largest, but I doubt that will make a difference here.

Upvotes: 0

bstamour
bstamour

Reputation: 7776

Are you ever initializing the variables sumSine and sumCosine in your functions? They're not guaranteed to start at zero, so when you call += inside your loop you could be adding computed values to garbage.

Try initializing those two variables to zero and see what happens, as other than that the code seems okay.

Upvotes: 4

Related Questions