简体   繁体   中英

Calculating sin(x) with Taylor series

Task: According to the Taylor Series of sin(x) calculate with using a double function named mysin pass it to a double variable. Take ax value from user and use the mysin function to calculate sin(x).

Sin()x 泰勒级数公式

Problem is program gives me wrong value of sin(x). I have been trying to solve that issue about 4 hours but couldn't find it. Is it because of sin(x) function or have I missed something in my code?

My Code:

#include <stdio.h>

double mysin(double x)
{
    double value = x;
    double sum = x;
    int neg_pos = 1;
    int fac = 1;
    
    int counter = 0;
    
    while(1)
    {
        neg_pos *= -1;
        fac += 2;
        
        value = value/(fac*(fac-1));
        value = value*x*x*neg_pos;

        sum += value;
        
        //printf("Hello");
        counter++;
        if (counter == 100) break;
    }
    return sum;
}

int main()
{
    double number;
    scanf("%lf",&number);
    printf("%g",mysin(number));
    //printf("%g",number);
}

The problem is that you're multiplying by neg_pos each step, which toggles between +1 and -1. That means the terms change sign only half the time, whereas they should change sign each time.

The fix is to just multiply by -1 each time rather than neg_pos .

Here's a working, slightly-simplified form of your program that calculates sin for a range of numbers from 0 to 3, showing the stdlib calculation to compare.

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

double mysin(double x) {
    double value = x;
    double sum = x;
    int fac = 1;
    
    for (int counter = 0; counter < 100; counter++) {
        fac += 2;
        value = -value*x*x/fac/(fac-1);
        sum += value;
    }
    return sum;
}

int main() {
    for (double x = 0.0; x < 3.0; x += 0.1) {
       printf("%g: %g %g\n", x, mysin(x), sin(x));
    }
}

You can also avoid the separate fac and counter variables, perhaps like this:

double mysin(double x) {
    double term=x, sum=x;
    for (int f = 0; f < 100; f++) {
        term = -term*x*x/(2*f+2)/(2*f+3);
        sum += term;
    }
    return sum;
}

From what I'm understanding you are not calculating the power correctly Firtsly use this:

#include <math.h>

Then create a factorial function:

int factorial(int x){
   int result = 1;
   for(int i = 1; i < x; i++){
      result += result * i;
   }
   return result;
}

And finally:

while(1)
 {
    neg_pos *= -1;
    fac += 2;
    
    power = pow(x,fac);
    fac = factorial(fac);

    sum += power/fac;
    
    //printf("Hello");
    counter++;
    if (counter == 100) break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM