c++ program for sum with cycle

Pages: 12
An approximation of $ pi $ "$ n $" can be calculated from the sum
$ pi_i = sum_ (j = 0) ^ i (-1) ^ j * 4 / (2j + 1) $
1. Develop a program that takes an integer, $ n $, and calculates the approximation of "grade $ n $".
2. Develop a second version that takes a double, $ epsilon $, and calculates an approximation of $ pi $ "
$ n $ "such that $ | pi_i - pi_ (i-1) | <epsilon $

i can't workout the second point, i wrote this but no way, advices?


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
30
31
32
33
34
35
36
37
 

#include<iostream>
#include<cmath>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main() {

 double n,i,j,sum=0,sum1=0,e,diff,diff1;

 cout<<"inserire e\t";
 cin>>e;

 for(diff=4-3/4;diff>e;diff=diff1){
	
 for(i=0;i<=j;i++){ sum+=pow(-1,j)*4/(2*j+1);};
                       
 for(i=1;i<=j;i++){ sum1+=pow(-1,j-1)*4/(2*(j-1)+1);};

diff=sum-sum1;

	
} 
cout<<diff;

}







I am not sure of what you are trying to do, but that loop is crazy.

At the start of the loop diff equals 4 - 3/4. You will run through the loop as long as diff is greater than e. With each time through the loop diff will be set to equal diff1. And diff1 has no value yet.

Back to the drawing board friend...
> i wrote this but no way, advices?
first, describe the issue better than «no way»
second, start with pseudocode or a diagram flow
make sure that you understand the problem correctly, you were asked to calculate pi, but your program returns `diff' which is the error on the approximation.
An approximation of $ pi $ "$ n $" can be calculated from the sum
$ pi_i = sum_ (j = 0) ^ i (-1) ^ j * 4 / (2j + 1) $

What does this even mean??? Why are there a bunch of "$" symbols? What is "sum_" ? Is "^" even supposed to be XOR or are you trying to show an exponent?

If it's supposed to be a math equation, maybe just draw a picture in MSPaint, upload to imgur, and then post link.
@icy1, it's in LaTeX (one of the popular standards for mathematical typsetting - at least amongst mathematicians and scientists; many programs can render it). You enclose inline formulae with $.

For the formula:
https://imgur.com/a/TeGfWbz

pi_i is the ith partial sum of the series for pi (which comes from 4*atan(1.0)). It doesn't converge very fast.

pow(-1,j) is one of my pet hates! For goodness' sake, just write sign = -sign; as you calculate each new term.
Last edited on
@lastchance

So what you are saying then, is that the post by zerbo1000, which looks like insain gibberish, might actually be more advanced mathematical genius?
It's just a markup language for writing mathematics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

double
sum(int n)
{
  int    sign = 1;
  double sum  = 0.0;
  for (int i = 0; i < n; ++i) {
    sum += sign * (1. / (2 * i + 1));
    sign = -sign;
  }

  return 4 * sum;
}

int
main()
{
  std::cout << "pi ≈ " << sum(1000) << '\n';
}

http://coliru.stacked-crooked.com/a/a0e3a9d3649c1207
Last edited on
lastchance ok, I've done a little latex, so where are the curly brackets { }

Could have linked https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 or
https://wikimedia.org/api/rest_v1/media/math/render/svg/cfa16105f38678c4b8151cd1ac1cd1a0a8d219c6 <-- this is an SVG image, I guess?!

So you basically took OP's code with a grain of salt and actually recalled some approximations for PI that looked like OP's code.

This is the equation I came up with to match the wiki image:
\dfrac{\pi}{4} = \sum_{k=0}^{\infty} \dfrac{(-1)^k}{2k + 1}


which can be plugged into http://latex2png.com/ for example

along same lines as mbozzi:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    int limit = 10'000'000;
    double sum = 0.0;
    double sign = 1.0;

    for (int k=0; k<=limit; ++k, sign = -sign)
        sum += sign / (2*k+1);

    cout << setprecision(12);
    cout << 4*sum << endl;
    cout << M_PI << "  <-- actual PI" << endl;

    return 0;
}


3.14159275359
3.14159265359  <-- actual PI
Last edited on
manga wrote:
So what you are saying then, is that the post by zerbo1000, which looks like insane gibberish, might actually be more advanced mathematical genius?


Hmm, I don't think I'd put it quite that highly!


icy1 wrote:
So you basically took OP's code with a grain of salt and actually recalled some approximations for PI that looked like OP's code.

No, I ignored the OP's code and read his/her formula
$ pi_i = sum_ (j = 0) ^ i (-1) ^ j * 4 / (2j + 1) $

(which - you and @mbozzi are right, I'm wrong - isn't LaTeX or even TeX, but is a similar markup language), typed it up in Microsoft word (almost exactly as written, in fact: see
http://pages.mtu.edu/~tbco/cm416/EquationEditor_main.pdf
or
https://www.unicode.org/notes/tn28/UTN28-PlainTextMath-v2.pdf
to use Word's equation editor without a mouse) and screenshot it. It can be recognised as (4 times) arctan(x) when x = 1, ... which is Pi. If you want to prove that, just expand 1/(1+x2) by the binomial theorem and integrate both sides. That particular standard integral is very common and useful; the corresponding series isn't, as the convergence is dreadful. Yes, it's called Leibnitz' theorem (which is a bit awkward, since there are several calculus-related formulae going by the same designation).

The convergence is terrible since the sum always lies between successive partial sums (it's a decreasing-in-magnitude alternating series) and the last term is of magnitude 1/(2N+1), so even 10 million terms is bound to give you an error in the 7th decimal place ... as your code demonstrates very effectively, icy1! ... as well as the accumulated round-off error of 10 million combinations.



And finally, back to answering the OP's original question ... !
- For the first code just form a sum to N terms.
- For the second code, stop adding terms when the last term added is less than epsilon - don't calculate an entire sum twice.
Last edited on
yes guys, before that i'll clarify the problem, that i expressed as a mess, can i know how tp format math formula here? as i've seen that the latex format don't works? thanks (icy1 you are quite quite close thanks, the problem is that i need and infinite loop for the sum beacuse i need that the condition for the sum to stop will be the "epsilon" and not the index of the sum, the index of the sum that will stop the sum to go have to be relative to the epsilon that satisfy the difference that i wrote up)
Last edited on
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>
using namespace std;

using INT = unsigned long long;
const INT NMAX = numeric_limits<INT> :: max();


double sumSeries( INT N, double epsilon )
{
   int sign = 1;
   double sum = 0.0, term = 4.0;
   for ( INT j = 0; j <= N && term > epsilon; j++ )
   {
      term = 4.0 / ( 2.0 * j + 1.0 );
      sum += sign * term;
      sign = -sign;
   }
   return sum;
}


double myPi( INT N          ) { return sumSeries(    N, 0.0     ); }


double myPi( double epsilon ) { return sumSeries( NMAX, epsilon ); }


int main()
{
   INT N;
   double epsilon;
   cout << setprecision( 12 );

   cout << "Enter N: ";   cin >> N;
   cout << "Pi_N = " << myPi( N ) << "\n\n";

   cout << "Enter epsilon: ";   cin >> epsilon;
   cout << "Pi(epsilon) = " << myPi( epsilon ) << "\n\n";

   cout << "Pi (formula) = " << 4.0 * atan( 1.0 ) << '\n';
}


Enter N: 10000000
Pi_N = 3.14159275359

Enter epsilon: 1e-7
Pi(epsilon) = 3.14159270359

Pi (formula) = 3.14159265359



@zerbo1000
If you change your formula
$ pi_i = sum_ (j = 0) ^ i (-1) ^ j * 4 / (2j + 1) $

to
$ \pi_i = \sum_{j = 0} ^ i (-1) ^ j * 4 / (2j + 1) $

it will (I think) be valid LaTeX.

Posting such a formula on the forum is tricky, but you can copy most symbols from a wordprocessor, and the format menu to the right has sub and superscripts.
Last edited on
thanks last chance, a part that if i run it on my DEV c++ it give like 5 error, but is really complicate coding, we have done just the cycles at lessons (it s an universitarian exercise), i'm sure i'm expected to do it with way few less string of code, without uning function, just nested cycles
zerbo1000 wrote:
a part that if i run it on my DEV c++ it give like 5 error


Maybe time to upgrade to at least C++11.

You can run it in cpp-shell (little gear-wheel icon to the top-right of the code sample).

If you don't want a separate function, just put its content where the function call is.
i already have the last version of DEV C++
i already have the last version of DEV C++


It's the compiler that's the issue, not the IDE. Run it in c++ shell or try another online compiler.
C++ shell what it is? i switched to code block anyway, dev c++ stops at c++5 i read
zerbo1000 wrote:
C++ shell what it is?


If you look at my code, you will see a little gear wheel icon just to the top right. Click on that and it will take you c++ shell. Then you can bookmark it. Exactly the same will work with @mbozzi and @icy1's codes (or any other code placed in code tags and with a main() function). @icy1's code may be easier for you to follow if you don't want to use separate functions.

Does my code run OK under your version of Code::Blocks? Sorry, I can't advise you on IDEs as I don't use them.
Last edited on
DEV c++ give like 5 error,

Do not say "like 5 error". Show the exact error messages. It is important and useful to understand and describe the error messages.

The C++ shell's compiler, when in C++98 mode, does comment lastchance's code with:
7:7: error: expected nested-name-specifier before 'INT'
8:7: error: 'INT' does not name a type
11:19: error: 'INT' was not declared in this scope
11:26: error: expected primary-expression before 'double'
11:41: error: expression list treated as compound expression in initializer [-fpermissive]
12:1: error: expected ',' or ';' before '{' token

Of these only the first is novel; the rest are caused by that first error.

The error is due to:
using INT = unsigned long long;
This is alias syntax that came in C++11. C++98 did not have it. There were only typedef:
typedef unsigned long long INT;

The C++ shell in C++98 mode does accept the code with that change, but still gives a warning:
7:23: warning: ISO C++ 1998 does not support 'long long' [-Wlong-long]

The C++98 did not have long long type, but the compiler happens to support that type as an extension. (Relying on compiler extensions is bad, for all compilers don't have them.)


Both DEV C++ and Code::Blocks are IDE's. They (probably) install some compiler (GCC?). They definitely use a compiler and you can change the compiler to a different one (e.g. newer version).

Furthermore, a compiler can support more than one language standard. GCC does. It defaults to one, but it has a command line option -std= that lets you choose another mode. You can tell your IDE to supply that option to the compiler.
anyway, i tried to do it simpler, yes, is the leibniz formula for pi greco, i have to give a number, and the last terms of the sum have to be littler than that number

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>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main() {

double pi=4,e;
int j=1;

cout<<"give me e";
cin>>e;


while (abs(pi)>e)
 
{
	pi=pi+((pow(-1,j)*4)/((2*j)+1))-((pow(-1,j-1)*4)/((2*(j-1))+1))

j++;

}

cout<<pi;

}


I also tried this variation inverting the formula of abs()<e cuz in the end is just the last term of the sum that matter, more clear than this i don't know what to write, but no result, i obtain ever 0 every double that i try, i write double with the . example 0.06

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main() {

double pi=0,e;
int j;

cout<<"give me e";
cin>>e;

  
  
for(j=0;j<2/e-1/2;j++) { pi=pi+(pow(-1,j)*4)/((2*j)+1) }


cout<<pi;

}


still, i think is ok the idea, just i don't know how to cycle the sum in j beacuse the cycle have to be rely to the number i give.

i tired to compile your program on codeblock but still i got many error, both syntax than of compiler i think.

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
30
31
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|1|iostream: No such file or directory|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|2|limits: No such file or directory|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|3|cmath: No such file or directory|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|4|error: syntax error before "namespace"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|4|warning: data definition has no type or storage class|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|6|error: syntax error before "INT"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|7|error: syntax error before "NMAX"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|7|error: `numeric_limits' undeclared here (not in a function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|7|error: syntax error before ':' token|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|10|error: syntax error before "N"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c||In function `sumSeries':|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: syntax error before "j"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: `j' undeclared (first use in this function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: (Each undeclared identifier is reported only once|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: for each function it appears in.)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: `N' undeclared (first use in this function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: `epsilon' undeclared (first use in this function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|14|error: syntax error before ')' token|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|20|error: syntax error before "return"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|24|error: syntax error before "N"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c||In function `myPi':|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|24|error: `N' undeclared (first use in this function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|27|error: redefinition of 'myPi'|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|24|error: previous definition of 'myPi' was here|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c||In function `main':|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|32|error: syntax error before "N"|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|34|error: `cout' undeclared (first use in this function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|36|error: `cin' undeclared (first use in this function)|
C:\Users\Alessandro\Documents\uni info robe\C++\es\1.7.2 tipo cplusplus.c|36|error: `N' undeclared (first use in this function)|
||=== Build failed: 25 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===| 
Last edited on
You don't get that many errors from a typo in code. You have got something set up wrong. As for the code, it builds just fine on my end. I use VS2015.
Pages: 12