calculation of tan with taylor series


I´m trying to write function which will calculate tan of angle in radians. I have to do it using taylor series using iterations, but only for first 13 nominators&denominators. Here´s the formula: http://upload.wikimedia.org/math/e/b/1/eb1675c46a1350a0983e57abf736b78c.png . Correct result for angle 1.024 after last iteration should be about 1.642..etc. Mine is about 2.528551e+000, which is completely wrong. I´ll be really thankful to all ideas what I´m doing wrong.

Here´s my function:

double ttan(double x)
{
double nominator[13] = {1,1,2,17,62,1382,21844,929569,6404582,443861162,18888466084,113927491862,58870668456604};//first 13 nominators
double *n = nominator;
double denominator[13] = {1,3,15,315,2835,155925,6081075,638512875,10854718875,1856156927625,194896477400625,49308808782358125,3698160658676859375};//first 13 denominators
double *d = denominator;

int i=0;
int j=0;
double t;
double s;
double xx=x*x;
s=t=x;


for(int test=0;test<13;test++)
{
t=t* xx* *(n+i)/ *(d+j);
s+=t;
printf("%e\n",s);
i++;
j++;
}


int main(int argc, char **argv)
{
if (argc<2)
return 1;
char *endptr;
double p = strtod(argv[1], &endptr);
ttan(p);
return 0;
}

Answers:


I have simplified your iteration loop and it now works correctly. I removed the unnecessary array pointers, and the two ints i and j which duplicated the loop variable test. But most importantly I initialised the array sum s to 0 instead of x, because the first term value (which is x) is taken care of in the first iteration, as both arrays have the values of 1 as their first element.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double ttan(double x)
{
    double nominator[13] = {1,1,2,17,62,1382,21844,929569,  
            6404582,443861162,18888466084,
            113927491862,58870668456604};//first 13 nominators
    double denominator[13] = {1,3,15,315,2835,155925,6081075,
            638512875,10854718875,1856156927625,194896477400625,
            49308808782358125,3698160658676859375};//first 13 denominators
    int test;
    double s = 0, xx=x*x;

    for(test=0;test<13;test++)
    {
        s += x * nominator[test] / denominator[test];
        printf("%e\n",s);
        x *= xx;
    }
    return s;
}

int main(int argc, char **argv)
{
    char *endptr;
    double p;
    if (argc<2)
       return 1;
    p = strtod(argv[1], &endptr);
    ttan(p);
    printf("\nMath library: tan(%f) = %f\n", p, tan(p));
    return 0;

}

My program ouput for 1.024

1.024000e+000
1.381914e+000
1.532034e+000
1.595748e+000
1.622822e+000
1.634327e+000
1.639216e+000
1.641294e+000
1.642177e+000
1.642552e+000
1.642712e+000
1.642716e+000
1.642744e+000

Math library: tan(1.024000) = 1.642829