[英]Problems while calculating value of sine with Taylor series
I'm trying to calculate 我正在努力计算
Using the following code. 使用以下代码。
#define PI 3.14
double ans;
double input1;
void toRad() {
input1 = input1 * PI / 180.0;
}
void sine(void) {
toRad();
ans = input1;
int i = 1;
for (; i < 15; i++) {
if (i % 2 == 0)
ans = ans + (ans * input1 * input1) / 2 * i * (2 * i + 1);
else
ans = ans - (ans * input1 * input1) / 2 * i * (2 * i + 1);
}
printf("%lf", ans);
}
I used iterative operations instead of pow
and factorial functions to get more precise values and more iterations. 我使用迭代运算代替pow
和factorial函数来获得更精确的值和更多的迭代。
But, for some reason, I got different outputs like -4000000E
. 但是,出于某种原因,我得到了不同的输出,如-4000000E
。 What can be the problem of this code? 这段代码有什么问题?
you have made a small mistake in writing the logic.check yourself until i=4. 你在编写逻辑时犯了一个小错误。自己检查直到i = 4。
if (i % 2 == 0)
ans = ans + (ans * input1 * input1) / 2 * i * (2 * i + 1);
else
ans = ans - (ans * input1 * input1) / 2 * i * (2 * i + 1);
instead of this you should create a factorial function so that it can be replaced by 而不是这个你应该创建一个阶乘函数,以便它可以被替换
if (i % 2 == 0)
ans = ans + (ans * input1 * input1) / factorial(2 * i + 1);
else
ans = ans - (ans * input1 * input1) / factorial(2 * i + 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.