Created
January 18, 2024 13:38
-
-
Save mibmo/8093842a541fdf40144d4ae6f7abfa70 to your computer and use it in GitHub Desktop.
Pi approximation in Java
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
public class PiApprox { | |
public static void main(String[] args) { | |
int precision = 16; | |
double targetPi = roundTo(Math.PI / 4, precision); | |
double pi = 0d; | |
int i = 0; | |
while (roundTo(pi, precision) != targetPi) { | |
int sign = i % 2 == 0 ? 1 : -1; | |
pi += 1d / (i++ * 2 + 1) * sign; | |
} | |
pi = roundTo(pi * 4, precision); | |
System.out.println("Target: " + targetPi); | |
System.out.println("Result: " + pi); | |
} | |
// Rounds number to a specific precision, i.e. roundTo(3.14159, 2) = 3.14) | |
public static double roundTo(double number, int precision) { | |
int exponent = (int) Math.pow(10, precision); | |
return (double) Math.round(number * exponent) / exponent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment