Answer the question
In order to leave comments, you need to log in
Calculate the approximate value of the infinite sum up to e=0.0001?
What's wrong here?
Here is the condition:
#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
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);
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 questionAsk a Question
731 491 924 answers to any question