R
R
Roma2016-01-20 19:39:41
C++ / C#
Roma, 2016-01-20 19:39:41

Calculate the approximate value of the infinite sum up to e=0.0001?

What's wrong here?
Here is the condition:
24414ba016d84a9b9e1d9332a8e83f0a.PNG

#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;

int fact(int n)
{
  if (n == 0 || n == 1) return 1;
  return fact(n - 1);
}

int main()
{

  int n, x;
  double r, memb;
  n = 0; 
  r = 0;

  x = 4;

  memb = (pow(-1, n)) * (pow(x, 2 * n)) / fact(2 * n);

  do
  {
    r += memb;
    memb = (pow(-1, n)) * (pow(x, 2 * n)) / fact(2 * n);

    n++;
  } while (fabs(memb) >= 0.0001);

  cout << r << endl;

  system("pause");
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-01-20
@k4roma

The factorial is incorrectly calculated. In your function, it is always equal to 1. And besides, the program is extremely suboptimally written.

double eps = 0.0001;
double sum = x;
double add = 1;
int i = 1;
do {
    add = -add*x*x/i/(i+1);
    sum += add;
    i += 2;
} while (fabs(add) >= eps);

V
Vladusch, 2016-01-27
@Vladusch

Offhand I’ll say: look towards the compensation summation algorithms, or as it is called Kahen summation . This algorithm makes it possible to achieve independence of the summation error from the number of terms, and in this case the maximum error will be equal to the error in the representation of a floating point number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question