Calculating PI with BigDecimal

∥☆過路亽.° 提交于 2021-02-10 20:20:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!