gpt4 book ai didi

使用泰勒级数编码 e^x 函数而不使用 math.h 和阶乘函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:18 29 4
gpt4 key购买 nike

我正在制作简单的计算器,它是 e^x 函数部分。

它适用于正数,但不适用于负数 x。我怎样才能让它也适用于负 x?`

double calculateEx(double x) {
double beforeResult = 1, afterResult = 1, term = 1, error = 1, i = 1, j;

while (error > 0.001) {
afterResult = beforeResult;
for (j = 1; j <= i; j++) {
term *= x;
}
term /= fact(i);
afterResult += term;
error = (afterResult - beforeResult) / afterResult;
if (error < 0) error * -1;
error *= 100;
beforeResult = afterResult;
term = 1;
i++;
}
return beforeResult;

double fact (double num) {
int i, j;
double total = 1;

for (i = 2; i <= num; i++) {
total = total * i;
}
return total;

最佳答案

通过泰勒级数计算指数

    exp(x) = 1 + x / 1 + x**2/2! + ... + x**n/n!

您不需要任何阶乘,请注意如果n-1第一项是

    t(n-1) = x**(n-1)/(n-1)!

然后

     t(n) = x**n/n! = t(n-1) * x / n;

这就是为什么您必须实现的是:

   double calculateEx(double x) {
double term = 1.0;
double result = term;

/*
the only trick is that term can be positive as well as negative;
we should either use abs in any implementation or putr two conditions
*/
for (int n = 1; term > 0.001 || term < -0.001; ++n) {
term = term * x / n;

result += term;
}

return result;
}

关于使用泰勒级数编码 e^x 函数而不使用 math.h 和阶乘函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251046/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com