Shortening a line in my script

I've created and edited the crap out of a script to calculate pi, and now I just want to know if I can make the line that carries out the calculation any shorter; everything else is fine.

Entire script:
1
2
3
4
5
6
7
8
9
10
//4-(4/3)+(4/5)-(4/7)+(4/9)...
#include <iostream>
#include <cmath>

int main(int s=1){
     double pi;
     for(double i=1;4/i>0.00001;i+=2,s*=-1){pi+=4/i*s;}
     std::cout<<pi;
     return 0;
}


This line:
 
for(double i=1;4/i>0.00001;i+=2,s*=-1){pi+=4/i*s;}


Now, I do realize that I can put the {pi+=4/i*s;} on a separate line, but I'm trying to minimize the number of lines while still making it look good, so that's why I'm asking, is there some magical function I'm not aware of to make things even simpler?
Last edited on
Not trying to minimise the number of lines :

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>

int main()
{
    double pi = 0 ; // initial value is zero, we will keep updating this in the loop
    
    int sign = 1 ; // sign multiplier for the next term

    const double numerator = 4.0 ; // constant for all terms
    double denominator = 1.0 ; // initial denominator

    double term ; // magnitude of the next term in the series
    const double epsilon = 0.00001 ; // we quit when term becomes less than this

    // while the magnitude of the next term is greater than epsilon
    while( ( term = numerator/denominator ) > epsilon )
    {
        pi += term * sign ; // add or subtract the term
        sign = -sign ; // flip the sign
        denominator += 2 ; // get to the next denominator
    }

    std::cout << "pi == approximately " << pi << '\n' ;
}

http://coliru.stacked-crooked.com/a/e7302a5375749c65
Thanks! May not answer my question, but very excellent in thoroughly explaining the mechanics. Well done!
could be off-topic but there is a simple (to understand) way to calculate the value of pi

https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80

1-(1/3)+(1/5)-(1/7)...=(π/4)

Therefore...

[1-(1/3)+(1/5)-(1/7)...]*4=π

And we can further simply it...

4-(4/3)+(4/5)-(4/7)...=π

This last equation is the one I use in my script, as it is the shortest way to express the equation.
https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Convergence

my bad, the above link will pinpoint what I am trying to point
Last edited on
Hmm... Interesting. I will try this and see what happens (for fun).
...
...
...
0_0
...
...
Later.
Last edited on
Topic archived. No new replies allowed.