Alternative way to do Taylor series in C

In my class, my professor wants us to use the functions to solve the Taylor series for sinX, cosX, and expX.

I solved this relatively quickly, but when I went to rotate it, he said he wanted me to use division first instead of multiplication, basically combining the power

and functions fact

. I have no idea why he wants it this way, because I get the right answer, but he won't accept the assignment until I do it.

I tried a few times to figure out the solution, but I'm not a Comp Sci master and don't do math in 6 years, so it shifts gears in my brain quite a bit. Any help would be much appreciated.

double power(double x, int n)
{
    int     i = 0;
    double  prod = 1.;

    for ( ; i++ < n; )
        prod = prod * x;

    return prod;
}

double fact (int n)
{
    int     i;
    double prod = 1.;

    for (i = 1; i <= n; i++)
        prod = prod * i;

    return prod;
}

double mySin(double x)
{
    int     i, sign;
    double  sum = 0;

    for (i = 0, sign = 1; i < 21; i++, sign = -sign)
        sum = sum + sign * power(x, 2 * i + 1)/ fact(2 * i + 1);
    return sum;
}

double myCos(double x)
{
    int     i, sign;
    double  sum = 0;

    for(i = 0, sign = 1; i < 21; i++, sign = -sign)
        sum = sum + sign *power(x,2 * i)/ fact(2 * i);
    return sum;
}

double myExp(double x)
{
    int     i, sign;
    double  sum = 0;

    for(i = 0, sign = 1; i < 21; i++, sign = sign)
        sum = sum + sign * power(x, i)/ fact(i);
    return sum;
 }

      

+3


source to share


1 answer


Using power and factorial functions is ineffective. For each term, you calculate the same set of products each time. You are also generating large numbers that can lead to loss of precision.

Take a look at the definition of each series (here ^

stands for cardinality and !

stands for factorial):

e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...
sin(x) = x - x^3/3! + x^5/5! - + x^7/7! + ...
cos(x) = 1 - x^2/2! + x^4/4! - + x^6/6! + ...

      



For e^x

each term is x/n

times greater than the last, where n

is a number. Similarly, for sin(x)

and cos(x)

each term is - x^2/((2n-1)*2n)

greater than the last one. Use this instead of a cardinality function and a factor function to calculate each subsequent term.

There's also a nice trick that involves a comparison that doesn't make sense mathematically but works due to the limited precision of floating point numbers to know when to stop evaluating terms. See if you can figure it out.

+4


source







All Articles