gpt4 book ai didi

c++ - 在 C++ 中计算欧拉数

转载 作者:太空狗 更新时间:2023-10-29 20:06:56 28 4
gpt4 key购买 nike

编写一个计算欧拉数 e 的程序。为此,首先编写一个接受参数 n 并返回结果 (1+1/n)n 的函数。当 n 接近无穷大时,此函数的极限接近 e。在您的主程序中,编写一个循环,使用递增的 n 值调用此函数。在每次迭代中,将 n 乘以 2(如果每次只将 1 加到 n,算法将不起作用)并在新近似值与之前的近似值相差小于 1e-8 时停止。现在你有一个很好的估计。所以在 main() 中,打印你的最佳近似值和生成它的数字 n。

我已经完成了 for 循环之前的所有操作。我不太明白在新的和以前的数字大致相同之后我应该如何停止 for-loop。

这是我的功能:

double euler_finder(double n)
{
return pow((1+1/n), n);
}

这是我在 main 方法中的 for 循环,在哪里???是我遇到问题的地方:

for (int i=0; i<????; i*=2) {

}

编辑:解决方案已发布,所以这里看起来像:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

double euler(int n);

int main()
{
int trialN = 4;

double guess1, guess2;

guess1 = euler(1);
guess2 = euler(2);

while( abs(guess1-guess2) > 1e-8 )
{
cout<< trialN << " " << guess2<<endl;
guess1 = guess2;
guess2 = euler( trialN );
trialN*=2;
}

cout<<setprecision(8)<<"e is approximately "<<guess2<<" and we got it with a value of ";
cout<<trialN<<" for n";

return 0;
}

double euler(int n)
{
return pow((1+1.0/n), n);
}

输出:

4 2.25
8 2.44141
16 2.56578
32 2.63793
64 2.67699
128 2.69734
256 2.70774
512 2.71299
1024 2.71563
2048 2.71696
4096 2.71762
8192 2.71795
16384 2.71812
32768 2.7182
65536 2.71824
131072 2.71826
262144 2.71827
524288 2.71828
1048576 2.71828
2097152 2.71828
4194304 2.71828
8388608 2.71828
16777216 2.71828
33554432 2.71828
67108864 2.71828
134217728 2.71828
e is approximately 2.7182818 and we got it with a value of 268435456 for n

最佳答案

首先,如果 i 从 0 开始,而你一直乘以 2,它不会进步太多。从 1 点开始。

其次,根据问题陈述,当你的近似值足够好时,你应该停止。所以循环停止条件不在 i 上,而是 abs(proper_E - your_approximation) > 1e-8

关于c++ - 在 C++ 中计算欧拉数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5413216/

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