How to add a very small number and a very large number

时间:2015-07-13 21:11:50

标签: java precision numerical-methods

I am pretty new to Java. I am learning numerical computation at the moment. How does one add and multiply a very small number and a very large number, say something of order $10^{-20}$ and something of order $10^{20}$ to arbitrary precision.

2 个答案:

答案 0 :(得分:2)

看一下BigDecimal课程。来自Javadoc:

  

不可变,任意精度的有符号十进制数。

  

BigDecimal类使用户可以完全控制舍入行为。

对于你的例子:

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal big = new BigDecimal("10e20");
        BigDecimal small = new BigDecimal("10e-20");
        BigDecimal ans = big.add(small);

        System.err.println("Answer: " + ans);
    }
}

Running提供以下内容:

$ java Main
Answer: 1000000000000000000000.00000000000000000010

答案 1 :(得分:0)

尝试以下操作(不计入零)。您可能会发现其他方法可以构建10 ^ 20/10 ^ -20更合适。

System.out.println( new BigDecimal("0.0000000000000000000000000000001").add( new BigDecimal
        ("100000000000000000000000000000000")));