Created
August 28, 2011 04:58
-
-
Save hans/1176260 to your computer and use it in GitHub Desktop.
Approximating pi with the Leibniz formula
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Leibniz { | |
public static void main(String[] args) { | |
Leibniz test = new Leibniz(); | |
System.out.println(test.leibnizPi(0)); | |
System.out.println(test.leibnizPi(-1)); | |
System.out.println(test.leibnizPi(-4)); | |
} | |
public double leibnizPi(int accuracy) { | |
double target_accuracy = Math.pow(10, accuracy); | |
double acc = 1.0; | |
int sub = 3; | |
int sign = -1; | |
while ( Math.abs(4.0 * acc - Math.PI) > target_accuracy ) { | |
acc += sign * ( 1.0 / sub ); | |
sign *= -1; | |
sub += 2; | |
} | |
return 4.0 * acc; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment