Domanda

Im just trying to get back into the way of programming in the Java language after having a rather large break so I decided to write a program that calculates PI to the users input number:

e.g. they enter 5, it would return 3.14159.

I've come across the Leibnez formula after a bit of searching but don't know how to implement in code. This seems to be a recurring problem so I'd like to rectify that. Anyone got any resources that demonstrate how to code mathematical formula?

For example, stuff that explains 1e6 and so on?

Cheers

È stato utile?

Soluzione

As a starting point you could use this code, it implements the sum notation as described here Leibniz formula for π

public class PI {
    public static void main( String[] args) {
        double PI4 = 1.0;
        for ( int i = 1 ; i <= 50 ; i++ ) {
            double nom = Math.pow( -1, i );
            double denom = 2 * i + 1;
            PI4 += nom / denom;
        }
        System.out.println( "result=" + PI4 * 4 );
    }

}

After 50 iterations the result is 3.1611986129870506

Altri suggerimenti

I recommend reading a good math tutorial online so you understand the math first. Then a good basic programming tutorial should do the job.

Stack Exchange's Math section is a good reference of math concepts as well.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top