A
A
avion2018-09-12 19:13:19
C++ / C#
avion, 2018-09-12 19:13:19

Error in c++ finding e^x?

This code finds e^x using the formula e^x = 1 + x + (x^2) / 2! + (x^3) / 3! and is executed until the term becomes less than 10^(-6):

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

//Функция нахождения факториал
double fl(int num) {
 int fl = 1;
 while (num) {
  fl *= num;
  num --;
 }
 return fl;
}

int main()
{
 setlocale(LC_CTYPE, "rus");

 double x, e, a = 1;
 int st = 2;

 cout << "input: ";
 cin >> x;
 e = 1 + x;

 while (a >= 10e-6)
  {
  a = pow(x, st) / fl(st);
  e += a;
  st++;
 }

 cout << "e^x: " << e;

 system("pause>nul");

 return 0;
}

The output for x = 2.1 displays the correct answer, but for x > 2.1, from which a negative number appears. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-09-12
@Rsa97

num —;What kind of operator is this?
Well, actually, of all the calculation options, you chose the most inefficient.
Such problems are solved by induction. It is necessary to express the next term of the series through the previous one. In this case,
y i = y i-1 * x / i
y 0 = 1
Accordingly, the cycle will be

res = 0;
y = 1;
i = 0;
do {
  res += y;
  y *= x / (++i);
} while (fabs(y) > 10e-6);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question