问题
This is my first time using a BigDecimal and I am having some troubles with it.
Here is my code:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
BigDecimal pi = new BigDecimal(4);
boolean plus = false;
for (int i = 3; i < 1000000; i += 2) {
if (plus) {
pi.add(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
} else {
pi.subtract(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
}
plus = !plus;
}
System.out.println(pi);
}
}
Why doesn't it calculate PI like it should but instead it gives me and answer of 4?
回答1:
You never change pi. Remember that BigDecimals are immutable, and you never change yours, i.e., you never assign it to a new value, and so you have to have somewhere
pi = ...
Inside your if/else would be a good place for this.
if (plus) {
pi = pi.add(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
} else {
pi = pi.subtract(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
}
From the first line from the BigDecimal API
Immutable, arbitrary-precision signed decimal numbers.
I would also change that scale of 2 to something better.
来源:https://stackoverflow.com/questions/25964754/calculating-pi-with-bigdecimal