我的算法课程教授给了我以下作业:
My professor from Algorithms course gave me the following homework:
编写一个C/C ++程序,以给定的eps精度计算欧拉数(e)的值.0.
Write a C/C++ program that calculates the value of the Euler's number (e) with a given accuracy of eps > 0.
提示:数字e = 1 + 1/1!+1/2!+ ... + 1/n!+ ... = 2.7172 ...可以计算为序列x_0,x_1,x_2,...的元素之和,其中x_0 = 1,x_1 = 1+ 1/1!,x_2 = 1 + 1/1!+1/2!,...,只要条件| x_(i + 1)-x_i |,加法继续进行> = eps有效.
Hint: The number e = 1 + 1/1! +1/2! + ... + 1 / n! + ... = 2.7172 ... can be calculated as the sum of elements of the sequence x_0, x_1, x_2, ..., where x_0 = 1, x_1 = 1+ 1/1 !, x_2 = 1 + 1/1! +1/2 !, ..., the summation continues as long as the condition |x_(i+1) - x_i| >= eps is valid.
正如他进一步解释的那样,eps是算法的精度.例如,精度可以是1/100| x_(i +1)-x_i |=(x_(i + 1)-x_i)的绝对值
As he further explained, eps is the precision of the algorithm. For example, the precision could be 1/100 |x_(i + 1) - x_i| = absolute value of ( x_(i+1) - x_i )
当前,我的程序以以下方式显示:
Currently, my program looks in the following way:
#include<iostream> #include<cstdlib> #include<math.h> #include<vector> // Euler's number using namespace std; double factorial(double n) { double result = 1; for(double i = 1; i <= n; i++) { result = result*i; } return result; } int main() { long double euler = 2; long double counter = 2; float epsilon = 2; do { euler+= pow(factorial(counter), -1); counter++; } while( (euler+1) - euler >= epsilon); cout << euler << endl; return 0; }当我实现停止条件| x_(i + 1)-x_i |时,问题就来了.>= eps(在哪里while((euler + 1)-euler> = epsilon);)输出是2.5而不是2.71828
The problem comes when I implement the stop condition |x_(i+1) - x_i| > = eps (line where is while( (euler+1) - euler >= epsilon);) The output is 2.5 instead of 2.71828
推荐答案| x_(i + 1)-x_i |>= eps 表示" x ( x_(i + 1))的 next 值与当前值大于或等于epsilon".
|x_(i+1) - x_i| > = eps means "the distance between the next value of x (x_(i+1)) and the current value of x (x_i) is greater or equal to epsilon".
您的代码正在向 x 添加一个并检查一个非常不同的条件:
Your code is adding one to x and checking a very different condition:
(euler+1) - euler >= epsilon这表示:迭代直到 euler + 1 (不是下一个 euler 的值!)减去当前值.",这与原始条件有很大的不同.另外,(euler + 1)-euler == 1 ,所以您要检查 epsilon 是否小于常数1.
This means: "iterate until euler + 1 (not the next value of euler!) minus the current value is...", which is very different from the original condition. Also, (euler+1) - euler == 1, so you're checking whether epsilon is less than a constant 1.
更多推荐
编写一个计算欧拉数的算法,直到
发布评论