Created
September 21, 2015 00:49
-
-
Save brianmcmichael/c0013520cf1e63120264 to your computer and use it in GitHub Desktop.
Pi Calculator Java
This file contains 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
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