uni

University stuff
git clone git://git.christosmarg.xyz/uni-assignments.git
Log | Files | Refs | README | LICENSE

sine-taylor.c (1124B)


      1 #include <stdio.h>
      2 #include <math.h>
      3 
      4 #define PI 3.141592654
      5 #define ACCURACY 0.000001
      6 
      7 double power(double, int);
      8 double factorial(int);
      9 
     10 
     11 int main(int argc, char *argv[])
     12 {
     13     double xDegrees, xRads, currentFrac, previousFrac, sine = 0;
     14     int exponent = 1, sign = 1;
     15 
     16     printf("x (in degrees): ");
     17     scanf("%lf", &xDegrees);
     18     xRads = xDegrees * (PI/180.0);
     19     
     20     currentFrac = power(xRads, exponent) / factorial(exponent);
     21     
     22     do
     23     {        
     24         sine += sign * currentFrac;
     25     
     26         exponent += 2;
     27 
     28         previousFrac = currentFrac;
     29         currentFrac = power(xRads, exponent) / factorial(exponent);
     30         
     31         sign *= -1;
     32     }
     33     while (fabs(previousFrac - currentFrac) > ACCURACY);
     34 
     35     printf("sin(%lf) = sin(%lf) = %lf rads\n", xDegrees, xRads, sine);
     36 
     37     return 0;
     38 }
     39 
     40 
     41 double power(double xRads, int exponent)
     42 {
     43     int i;
     44     double value;
     45 
     46     for (i = 0, value = 1; i < exponent; i++)
     47         value *= xRads;
     48 
     49     return value;
     50 }
     51 
     52 
     53 double factorial(int exponent)
     54 {
     55     int i;
     56     double fac;
     57 
     58     for (i = 1, fac = 1; i <= exponent; i++)
     59         fac *= i;
     60 
     61     return fac;
     62 }