Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

c++ - Write an algorithm that compute the Euler's number until

My professor from Algorithms course gave me the following homework:

Write a C/C++ program that calculates the value of the Euler's number (e) with a given accuracy of eps > 0.

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.

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;
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

|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".

Your code is adding one to x and checking a very different condition:

(euler+1) - euler >= epsilon

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...