Fundamental Algorithms Analysis (004)-Calculate Pi[计算Π值][C++/Java]

Calculate π \pi π

Here π \pi π is estimated by Leibniz formula.
As our hobby, we always keep code short and efficient and no more than Python or other languages could be.

For π \pi π (C++)

double getPi(long End){
    double pi=0;
    long denominator=-1,numerator=-4,i=0;
    while(i++<End)pi+=(numerator*=-1)*1./(denominator+=2);//Leibniz formula
    return pi;
}

Main test(C++)

#include 
#include 
using namespace std;
double getPi(long End){
    double pi=0;
    long denominator=-1,numerator=-4,i=0;
    while(i++<End)pi+=(numerator*=-1)*1./(denominator+=2);//Leibniz formula
    return pi;
}
int main()
{
    double pi=getPi(9999999999);//it costs much time
    cout<<setprecision(50)<<pi;
    //3.1415926503687150450616627495037391781806945800781
}

Main test (Java)

public class Main {
    static double getPi(long End){
        double pi=0;
        long denominator=-1,numerator=-4,i=0;
        while(i++<End)pi+=(numerator*=-1)*1./(denominator+=2);//Leibniz formula
        return pi;
    }
    public static void main(String[] args){
        double pi=getPi(999999999);//it costs much time
        System.out.println(pi);
        //3.1415926545880506
    }
}

你可能感兴趣的:(c++,java,算法)