Skip to content

Instantly share code, notes, and snippets.

@mibmo
Created January 18, 2024 13:38
Show Gist options
  • Save mibmo/8093842a541fdf40144d4ae6f7abfa70 to your computer and use it in GitHub Desktop.
Save mibmo/8093842a541fdf40144d4ae6f7abfa70 to your computer and use it in GitHub Desktop.
Pi approximation in Java
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