C++ program

Hello! How can I make a program in C ++, some given x and eps determined by input, calculate the sum of those terms that are greater in absolute value than eps. Compare the results with the exact value of the function for which this sum determines the approximate value when x lies in the interval (- R, R), the formula itself is written in while, I just don't understand what to do next,the code is almost finished, but what else to add?

1
2
3
4
5
6
7
8
9
10
k=1;
n=3;
sum=1;
while(eps< ( x^(n+1))/n!){
sum+=((-1)^k * x^(n+1))/n!;
n+=2;
k++;
}
print("difference of values:")
print((sin x/x) -sum)
Last edited on
this code isnt finished at all ... its not c++ but from a math textbook or another language.

^ is logical xor.
! is logical not.
print does not exist.

so the first thing to do is convert the math to c++.
you can use pow(base, exponent).
factorials are best as a lookup table:
uint64_t fact[] = {1,1,2,6,24, .... fill this out as far as you need it};

make sure you have floating point types or that division will be integer division, which says that 2/3 is zero.

then you get something like
while(eps < (pow(x,n+1)/fact[n])
{
etc
}
cout << answer << endl; //print in c++
Last edited on
The formula is for the summation of

1 - x^4/3! + x^6/5! - x^8/7!.... (where ^ is power and ! is factorial).

As such, you don't need to calculate powers or factorial. For each iteration, the numerator is the previous one * x * x * -1 and the denominator is the previous one * n * (n - 1) and with n incrementing by 2 each iteration.
@sukuna231
The formula you give in the "while" statement is NOT for the function you put in the printf statement. Which one of those two is correct?

If the one in the printf statement is correct (it's called the sinc() function: sin(x)/x ) then the one in the "while" statement (and the following line) would have n-1 in it and not n+1.



Here's an attempt assuming the one in the printf statement is correct:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cmath>
using namespace std;

double series( double x, double eps )
{
   double term = 1.0;
   double sum = term;
   for ( int n = 3; abs( term ) > eps; n += 2 )
   {
       term *= -x * x / n / ( n - 1 );
       sum += term;
   }
   return sum;
}


double sinc( double x )
{
   return abs( x ) < 1.0e-30 ? 1 : sin( x ) / x;
}


int main()
{
   double x, eps;
   cout << "Input x and epsilon: ";   cin >> x >> eps;
   cout << "Series: " << series( x, eps ) << "     sinc( x ): " << sinc( x ) << '\n';
}


Input x and epsilon: 10 1e-10
Series: -0.0544021     sinc( x ): -0.0544021
Last edited on
this formula is used here:
sin(x)/x=1-x^2/3!+x^4/5!-x^6/7!+....
Sukuna231 wrote:
this formula is used here:
sin(x)/x=1-x^2/3!+x^4/5!-x^6/7!+....


So the printf statement was correct, but your original while statement (and its successor) should have had n-1, not n+1.
Topic archived. No new replies allowed.