Need help programming with Mclauren series and Taylor series!

Posted by user352258 on Stack Overflow See other posts from Stack Overflow or by user352258
Published on 2010-05-27T18:29:51Z Indexed on 2010/05/27 18:51 UTC
Read the original article Hit count: 449

Ok so here's what i have so far:

#include <stdio.h>
#include <math.h>
//#define PI 3.14159

int factorial(int n){
  if(n <= 1)
    return(1);
  else
    return(n * factorial(n-1));
}

void McLaurin(float pi){
  int factorial(int);
  float x = 42*pi/180;
  int i, val=0, sign;

  for(i=1, sign=-1; i<11; i+=2){
    sign *= -1; // alternate sign of cos(0) which is 1
    val += (sign*(pow(x, i)) / factorial(i));
  }

  printf("\nMcLaurin of 42 = %d\n", val);
}

void Taylor(float pi){
  int factorial(int);
  float x;
  int i;
  float val=0.00, sign;
  float a = pi/3;

  printf("Enter x in degrees:\n");
  scanf("%f", &x);
  x=x*pi/180.0;
  printf("%f",x);

  for(i=0, sign=-1.0; i<2; i++){
    if(i%2==1)
      sign *= -1.0; // alternate sign of cos(0) which is 1
    printf("%f",sign);
    if(i%2==1)
      val += (sign*sin(a)*(pow(x-a, i)) / factorial(i));
    else
      val += (sign*cos(a)*(pow(x-a, i)) / factorial(i));
    printf("%d",factorial(i));
  }

  printf("\nTaylor of sin(%g degrees) = %d\n", (x*180.0)/pi, val);
}

main(){
  float pi=3.14159;
  void McLaurin(float);
  void Taylor(float);

  McLaurin(pi);
  Taylor(pi);
}

and here's the output:

McLaurin of 42 = 0
Enter x in degrees:
42
0.733038-1.00000011.0000001
Taylor of sin(42 degrees) = -1073741824

I suspect the reason for these outrageous numbers goes with the fact that I mixed up my floats and ints? But i just cant figure it out...!! Maybe its a math thing, but its never been a strength of mine let alone program with calculus. Also the Mclaurin fails, how does it equal zero? WTF! Please help correct my noobish code. I am still a beginner...

© Stack Overflow or respective owner

Related posts about c

    Related posts about programming-languages