Skip to content

Instantly share code, notes, and snippets.

@brianmcmichael
Created September 21, 2015 00:49
Show Gist options
  • Save brianmcmichael/c0013520cf1e63120264 to your computer and use it in GitHub Desktop.
Save brianmcmichael/c0013520cf1e63120264 to your computer and use it in GitHub Desktop.
Pi Calculator Java
package picalc;
import java.math.BigDecimal;
import java.math.MathContext;
public class Main {
public static void main(String[] args) {
BigDecimal num = new BigDecimal(4.0);
BigDecimal pi = new BigDecimal(0);
boolean plus = true;
BigDecimal den = new BigDecimal(1);
BigDecimal max = new BigDecimal(1000000000);
while (den.compareTo(max) == -1) {
if (plus) {
pi = pi.add(num.divide(den, MathContext.DECIMAL128));
plus = false;
} else {
pi = pi.subtract(num.divide(den, MathContext.DECIMAL128));
plus = true;
}
den = den.add(new BigDecimal(2));
System.out.println(pi.toString());
}
System.out.println("--------------------------------\n"
+ "Calculated Pi = " + pi + "\n"
+ "Math Static Pi = " + Math.PI + "\n"
+ "--------------------------------");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment