I'm trying to make an Android phone calculate n decimals of Pi. For this I'm using this code:
public class Pi {
private static final BigDecimal TWO = new BigDecimal(2);
private static final BigDecimal FOUR = new BigDecimal(4);
private String nummer;
public void pi(final int SCALE) {
BigDecimal a = ONE;
BigDecimal b = ONE.divide(sqrt(TWO, SCALE), SCALE, ROUND_HALF_UP);
BigDecimal t = new BigDecimal(0.25);
BigDecimal x = ONE;
BigDecimal y;
while (!a.equals(b)) {
y = a;
a = a.add(b).divide(TWO, SCALE, ROUND_HALF_UP);
b = sqrt(b.multiply(y), SCALE);
t = t.subtract(x.multiply(y.subtract(a).multiply(y.subtract(a))));
x = x.multiply(TWO);
}
a.add(b).multiply(a.add(b)).divide(t.multiply(FOUR), SCALE, ROUND_HALF_UP);
number(a);
}
public void number(BigDecimal a) {
//nummer = a.toString().length();
nummer = a.toString();
}
public String returnNum() {
return nummer;
}
public static BigDecimal sqrt(BigDecimal A, final int SCALE) {
BigDecimal x0 = new BigDecimal("0");
BigDecimal x1 = new BigDecimal(Math.sqrt(A.doubleValue()));
while (!x0.equals(x1)) {
x0 = x1;
x1 = A.divide(x0, SCALE, ROUND_HALF_UP);
x1 = x1.add(x0);
x1 = x1.divide(TWO, SCALE, ROUND_HALF_UP);
}
return x1;
}
This works like a charm on any computer but when I try to run this on my Android tablet it decides that Pi is 0.8 something. Why does this miss calculation occur and how can I make this work?
You are missing a bit from your calculation. The line :
a.add(b).multiply(a.add(b)).divide(t.multiply(FOUR), SCALE, ROUND_HALF_UP);
is not being assigned to anything. Assign this to something and print that value out and you'll find your calculation works.
BigDecimal pi = a.add(b).multiply(a.add(b)).divide(t.multiply(FOUR), SCALE, ROUND_HALF_UP);
System.out.println(pi)
This gives me the correct answer.
For those that are interested, the algorithm can be found on wikipedia
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With