c - Why isn't my code accurate when I change the numberOfTerms? -


#include <stdio.h>  double pi = 3.141592653589;  int numberofterms = 5;   int factorial(int n) {     if(n > 1)         return n * factorial(n - 1);     else         return 1; }  double degreestoradian( double degrees )     {          return degrees * pi / 180;     }   void cosine(double cos){         int x = 0;         double ans = 1;         int exponent = 2;         int isplus = 0;         for(x; x < numberofterms - 1; x++){             if(isplus == 0){                 ans -= (pow(cos, exponent))/factorial(exponent);                 exponent += 2;                 isplus = 1;             }else{                 ans += (pow(cos, exponent))/factorial(exponent);                 exponent += 2;                 isplus = 0;             }         }         printf ("%.12f \t", ans);     }  void sine(double sin){         int x = 0;         double ans = sin;         int exponent = 3;         int isplus = 0;         for(x; x < numberofterms - 1; x++){             if(isplus == 0){                 ans -= (pow(sin, exponent))/factorial(exponent);                 exponent += 2;                 isplus = 1;             }else{                 ans += (pow(sin, exponent))/factorial(exponent);                 exponent += 2;                 isplus = 0;             }         }         printf ("%.12f \n", ans);     }  int main() {     double j = -180.00;     printf(" ");     printf("\n\n");          (j; j <= 180; j += 5){             printf("%.2f \t", j);             printf( "%.12f \t", degreestoradian(j));             cosine(degreestoradian(j));             sine(degreestoradian(j));         }  return 0;    } 

i'm using taylor series find sin , cosine of number when change numberofterms 10 or 15 becomes inaccurate(waaaaaaaaayy off), need change make accurate? (yeah functions not optimal lel)

i [warning] incompatible implicit declaration of built-in function 'pow' if matters.

let assume keep value of numberofterms 10. then, in cosine , sine functions, in for loop, incrementing exponent 2 every time. and, using factorial of exponent in denominator.

if loop runs 9 times, value exponent increase 2, 4, 6, 8, 10, 12, 14, 16, 18.

we know 14! = 87178291200. signed int (which used return result of factorial function) can hold positive value 2147483647. there occurs overflow.

i suggest use double (or unsigned long long) return type , parameter of factorial function. not try compute factorials of large numbers not fit in data type in c.

also, since have not defined pow function yourself, think missing #include<math.h> @ top.

another suggestion, define pi symbolic constant rather global variable.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -