C 用泰勒级数编码e^x函数而不使用math.h和阶乘函数
我正在制作一个简单的计算器,它是e^x函数的一部分 它适用于正数,但不适用于负x。 如何使它也适用于负x`C 用泰勒级数编码e^x函数而不使用math.h和阶乘函数,c,exponential,taylor-series,ex,C,Exponential,Taylor Series,Ex,我正在制作一个简单的计算器,它是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++)
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 calculateEx(双x){
双精度前结果=1,后结果=1,项=1,误差=1,i=1,j;
而(误差>0.001){
后结果=前结果;
对于(j=1;j好的,正如我在上面的评论中所写的,如果可能的话,我会使用
,但是既然你问了这个问题:
< >用负数工作,如果<代码> x>代码>是否定的,考虑如果否定它会发生什么。
您可以通过存储一个阶乘表来摆脱阶乘函数。您不需要那么多的元素
好的,正如我在上面的评论中所写的,如果可能的话,我会使用
,但是既然你问了这个问题:
< >用负数工作,如果<代码> x>代码>是否定的,考虑如果否定它会发生什么。
您可以通过存储一个阶乘表来摆脱阶乘函数。您不需要那么多的元素
用泰勒级数计算指数时
exp(x) = 1 + x / 1 + x**2/2! + ... + x**n/n!
您不需要任何阶乘,请注意,如果n-1
th项为
t(n-1) = x**(n-1)/(n-1)!
然后
这就是为什么您必须实施的全部内容是:
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;
}
double calculateEx(双x){
双项=1.0;
双结果=期限;
/*
唯一的诀窍是这个术语可以是正的,也可以是负的;
我们要么在任何实现中使用abs,要么在两种情况下使用abs
*/
对于(int n=1;项>0.001 | |项<-0.001;++n){
术语=术语*x/n;
结果+=期限;
}
返回结果;
}
通过泰勒级数计算指数时
exp(x) = 1 + x / 1 + x**2/2! + ... + x**n/n!
您不需要任何阶乘,请注意,如果n-1
th项为
t(n-1) = x**(n-1)/(n-1)!
然后
这就是为什么您必须实施的全部内容是:
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;
}
double calculateEx(双x){
双项=1.0;
双结果=期限;
/*
唯一的诀窍是这个术语可以是正的,也可以是负的;
我们要么在任何实现中使用abs,要么在两种情况下使用abs
*/
对于(int n=1;项>0.001 | |项<-0.001;++n){
术语=术语*x/n;
结果+=期限;
}
返回结果;
}
为什么不使用
?exp
函数可能比用C轻松编写的任何代码都要快(在某些情况下,它可能只是一条机器指令,但至少可以预期库编写器会将其优化到一英寸以内).Small code review red flag:您有三个循环。这真的有必要吗?这是我的学校作业,教授下令不要使用math.h库。我以后会在我自己的作业中使用它@alastair@KerrekSB我将再次检查这三个循环。谢谢您的建议:)为什么不使用
?exp
函数可能比用C轻松编写的任何代码都要快(在某些情况下,它可能只是一条单机指令,但至少可以预期库编写者会将其优化到一英寸的寿命内).Small code review red flag:您有三个循环。这真的有必要吗?这是我的学校作业,教授下令不要使用math.h库。我以后会在我自己的作业中使用它@alastair@KerrekSB我将再次检查这三个循环。谢谢您的建议:)