Created
December 22, 2016 22:14
-
-
Save peterjurkovic/1fdedfd26c7ed53297376afa919b9c75 to your computer and use it in GitHub Desktop.
Compute PI
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
package couchbase.test; | |
import java.math.BigDecimal; | |
public class JoinDemo { | |
private final static BigDecimal FOUR = BigDecimal.valueOf(4); | |
private final static int roundingMode = BigDecimal.ROUND_HALF_EVEN; | |
private static BigDecimal result; | |
public static void main(String[] args) { | |
Runnable r = () -> { | |
result = JoinDemo(50_000); | |
}; | |
Thread t = new Thread(r); | |
t.start(); | |
try{ | |
System.out.println("Joining.."); | |
t.join(); | |
}catch (Exception e) { | |
System.out.println(e); | |
} | |
System.out.println(result); | |
} | |
public static BigDecimal computePi(int digits){ | |
int scale = digits + 5; | |
BigDecimal arctan1_5 = arctan(5, scale); | |
BigDecimal arctan239 = arctan(239, scale); | |
BigDecimal pi = arctan1_5.multiply(FOUR) | |
.subtract(arctan239).multiply(FOUR); | |
return pi.setScale(digits, BigDecimal.ROUND_HALF_UP); | |
} | |
private static BigDecimal arctan(int invertX, int scale) { | |
BigDecimal result, number, term; | |
BigDecimal invX = BigDecimal.valueOf(invertX); | |
BigDecimal invX2 = BigDecimal.valueOf(invertX * invertX); | |
number = BigDecimal.ONE.divide(invX, scale, roundingMode); | |
result = number; | |
int i = 1; | |
do{ | |
number = number.divide(invX2, scale, roundingMode); | |
int denom = 2 * i + 1; | |
term = number.divide(BigDecimal.valueOf(denom), scale, roundingMode); | |
if((i % 2) != 0) | |
result = result.subtract(term); | |
else | |
result =result.add(term); | |
i++; | |
} | |
while(term.compareTo(BigDecimal.ZERO) != 0); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment