我如何在 c 中编写 exp(x)?
How can I code exp(x) in c?
exp 函数有一个系列,如下所示:
exp(x) = (x^0)/0! + (x^1)/1! + (x^2)/2! + (x^3)/3! + ···
。我正在尝试针对不同的 x 值计算它,用计算器检查我的结果,我发现对于大值,例如 20,我的结果停止增加并卡在一个几乎是真实值的值中。我得到 485165184.00
,实际值为 485165195.4
。
我必须在 for 循环或递归函数中执行此代码,因为它是家庭作业。
我的代码如下所示
#include <stdio.h>
#define N 13
#define xi 3
double fun7(int n, int m){
int i;
double res=1, aux=0;
for(i=1, aux=1; i<(n+1); i++){
res += aux;
aux *= m;
aux /= i;
}
return res-1;
}
int main() {
int a, b, pot, x[xi];
float R[N][xi];
x[0] = 5;
x[1] = 10;
x[2] = 20;
for(b=0; b<xi; b++){
for (a=0, pot=1; a<N; a++){
R[a][b] = fun7(pot, x[b]);
pot *= 2;
}
}
for(b=0; b<xi; b++){
for (a=0, pot=1; a<N; a++){
printf("%d\t%f\n", pot, R[a][b]);
pot *= 2;
}
printf("\n");
}
return 0;
}
float
数据类型通常可以表示精度略高于 7 位小数的数字。
485165184 有 9 个十进制数字。就 float
而言,最后两位数字只是无意义的噪音。您确实应该显示 4.851652e8,这是具有给定精度级别的 exp(20) 的正确值。
如果您想提高精度,请尝试使用 double
或 long double
数据类型。
exp 函数有一个系列,如下所示:
exp(x) = (x^0)/0! + (x^1)/1! + (x^2)/2! + (x^3)/3! + ···
。我正在尝试针对不同的 x 值计算它,用计算器检查我的结果,我发现对于大值,例如 20,我的结果停止增加并卡在一个几乎是真实值的值中。我得到 485165184.00
,实际值为 485165195.4
。
我必须在 for 循环或递归函数中执行此代码,因为它是家庭作业。
我的代码如下所示
#include <stdio.h>
#define N 13
#define xi 3
double fun7(int n, int m){
int i;
double res=1, aux=0;
for(i=1, aux=1; i<(n+1); i++){
res += aux;
aux *= m;
aux /= i;
}
return res-1;
}
int main() {
int a, b, pot, x[xi];
float R[N][xi];
x[0] = 5;
x[1] = 10;
x[2] = 20;
for(b=0; b<xi; b++){
for (a=0, pot=1; a<N; a++){
R[a][b] = fun7(pot, x[b]);
pot *= 2;
}
}
for(b=0; b<xi; b++){
for (a=0, pot=1; a<N; a++){
printf("%d\t%f\n", pot, R[a][b]);
pot *= 2;
}
printf("\n");
}
return 0;
}
float
数据类型通常可以表示精度略高于 7 位小数的数字。
485165184 有 9 个十进制数字。就 float
而言,最后两位数字只是无意义的噪音。您确实应该显示 4.851652e8,这是具有给定精度级别的 exp(20) 的正确值。
如果您想提高精度,请尝试使用 double
或 long double
数据类型。