cphoenix
cphoenix

Reputation: 19

Arctan Taylor Series in C

I need to perform the Taylor Series for arctangent 50 times. Meaning 50 numbers between the domain of the arctan Taylor Series which is [-1,1]. I've tested it out with manual user input and it works fine, but the for loop for the 50 different inputs which I increment in the code by 0.01 and their corresponding results has been unsuccessful. I've tried everything I could think of so far, I'm out of ideas. Any help would be appreciated. Is there an issue with my brackets surrounding the Taylor Series that's conflicting with the other for loop? I've suspected it was the brackets but nothings worked when I attempted to fix it.

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

main (void) {
    double n;
    double x;
    double tSeries=0.0;
    double t2;
    double t1;

    for(n=0;n<=50;++n) {
        for(x=-1;x<=1;x=x+0.01) {

            t1=(pow(x,2*n+1))*pow(-1,n);
            t2=t1/(2*n+1);
            tSeries+=t2;

            printf("arctan(%lf)=%lf\n",x,tSeries);
        }
    }
    return 0;
}

Upvotes: 1

Views: 2508

Answers (2)

gusgw
gusgw

Reputation: 96

In the code you've posted the inner loop is over the variable x, and the outer loop is over the power n.

I think you want to sum over values of n for each value of x, so the loop over n should be the inner loop.

I think you also need to zero your sum, tSeries for each value of x.

Finally, I expect you want to print the answer after calculating the sum, so printf should be outside the n loop.

There are a few tricks to the evaluation of power series. I like Numerical Recipes for this sort of thing. Try chapter 5 on the evaluation of functions. (Numerical Recipes in C, Press et al., 2nd Ed., 1992, CUP.)

One thing to note right away is that with the upper limit of the power series fixed, you are evaluating a polynomial. Section 5.3 of my copy of NR recommends strongly against using a sum of calls to pow(). They are quite firm about it!

Let me know if you want me to post correct code.

Upvotes: 2

deamentiaemundi
deamentiaemundi

Reputation: 5525

You got the loops mixed, the inner one goes out and vice versa.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
  double n;
  double x;
  double tSeries = 0.0;
  double t2;
  double t1;

  for (x = -1; x <= 1; x += 0.01) {
    for (n = 0; n <= 50; n++) {
      t1 = (pow(x, 2 * n + 1)) * pow(-1, n);
      t2 = t1 / (2 * n + 1);
      tSeries += t2;
    }
    printf("arctan(%lf)=%lf (%lf)\n", x, tSeries, atan(x));
    tSeries = 0.0;
  }
  return 0;
}

Upvotes: 1

Related Questions