泰勒级数中sin(x)的公式(代码下的图片)。通常,如果在步骤2中输入Start 1和end 20,则控制台在x=9之后输出'-nan‘;sin(X)和Taylor应该是相同的;例如:
X= 9;sin(x) = 0.412118;taylor = 0.412118
X= 11;sin(x) = -0.99999;taylor -0.999976;
X= 13;sin(x) = 0.420167;taylor = -nan;
一直这样,我需要一些帮助,这是为了我的实验室
#include <stdio.h>
#include <math.h>
int main(void) {
float a, b, left, right, eps = 0.00001, step, x, add = 1, chis, znam, fact, sum = 0, delta;
printf("Plese enter your start: ");
scanf("%f", &a);
printf("Your end: ");
scanf("%f", &b);
printf("and step: ");
scanf("%f", &step);
if (b < a || a < eps) {
printf("Your inputs aren't correct");
return -1;
}
printf("\tX\t sin(x)\tTaylor\t Delta\n");
for (x = a; x < b; x += step) {
printf(" x = %9f\t", x);
left = sin(x);
printf("%9f", left);
chis = -x;
znam = 1;
sum = 0;
add = 1;
fact = 1;
while (fabs(add) > eps) {
add = -1 * chis / znam;
sum += add;
chis *= -1 * (x * x);
fact++;
znam *= fact * (fact + 1);
fact++;
}
printf(" %9f ", sum);
printf("%e\n", fabs(left - sum));
}
}

发布于 2022-10-20 19:43:51
您不需要计算幂或阶乘:
double tailor(double x, unsigned n)
{
double result = x;
double part = x;
int sign = -1;
for(unsigned i = 1; i <= n; i++)
{
for(unsigned dv = 2 * (i - 1) + 1 + 1; dv <= 2 * i + 1; dv++)
{
part *= x / (double)dv;
}
result += sign * part;
sign *= -1;
}
return result;
}
int main(void)
{
for(unsigned n = 10; n < 60; n++)
printf("n = %u : %.60f\n", n, tailor(13, n));
}https://godbolt.org/z/b1z3rszh8
您可以很容易地添加epsilon检查,而不是从调用方填充n。
https://stackoverflow.com/questions/74145000
复制相似问题