Skip to content

Instantly share code, notes, and snippets.

@hans
Created August 28, 2011 04:58
Show Gist options
  • Save hans/1176260 to your computer and use it in GitHub Desktop.
Save hans/1176260 to your computer and use it in GitHub Desktop.
Approximating pi with the Leibniz formula
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