[英]Using a Taylor series to find sin(x) in C
I have an assignment where my professor wants us to calculate sin(x) using a taylor series.我有一个任务,我的教授希望我们使用泰勒级数计算 sin(x)。 He wants us to stop the iterations when the difference between two consecutive fractions is less than 10^-6.他希望我们在两个连续分数之间的差异小于 10^-6 时停止迭代。
I ended up approaching the problem by saying that for example x^5/5.我最终通过说例如 x^5/5 来解决这个问题。 is the same as (x^3/3.) * (x^2/4*5) and that this is true for all the fractions.与 (x^3/3.) * (x^2/4*5) 相同,并且对于所有分数都是如此。 So I can just keep the previous fraction I calculated and use it on the next iteration.所以我可以保留我计算的前一个分数并在下一次迭代中使用它。 Problem is the number I end up with is a bit off from its actual sin and I can't figure out why:Thanks in advance.问题是我最终得到的数字与它的实际罪恶有点不同,我不知道为什么:提前谢谢。 Here is my code:这是我的代码:
#include <stdio.h>
#include <Math.h>
#define pi 3.14159265358979323846
int main(int argc, int **argv){
int sign = -1, pwr = 3;
double previous, current, rad,sum, degr;
printf("Calculating sin using Taylor Series\n\n");
printf("Give degrees: ");
scanf("%lf", °r);
// translate to rads
rad = degr*(pi/180);
sum = rad;
previous = rad;
do{
current = (previous * pow(rad, 2))/(pwr* pwr-1);
sum += sign*current;
pwr += 2;
sign *= -1;
}
while(abs(current - previous) > pow(10, -6));
printf("The sin of %lf degrees is ", degr);
printf("%.6f\n", sum);
printf("%.6f", sin(rad));
return 0;
}
You're using the abs
function, which expects an int
and returns an int
.您正在使用abs
function,它需要一个int
并返回一个int
。 This results in the loop existing if the difference between the current and prior term is less than 1 as it will set diff
to 0.如果当前项和先前项之间的差异小于 1,这将导致循环存在,因为它将diff
设置为 0。
Instead, you want fabs
which expects and returns a double
.相反,您需要fabs
期望并返回一个double
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.