简体   繁体   中英

Java loss of precision with large double

 double lnumber = Math.pow(2, 1000);

prints 1.0715086071862673E301

Things I have tried

I have tried to expand this number by using BigDecimal Class:

 String strNumber = new BigDecimal(Double.toString(lnumber)).toPlainString();

this just prints:

10715086071862673000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

I also tried to use DecimalFormat:

    DecimalFormat df = new DecimalFormat("#");
    df.setMaximumFractionDigits(0);
    String strNumber = String.valueOf(df.format(lnumber));

prints the same thing:

10715086071862673000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

The actual answer according to Wolfram Alpha is

在此处输入图片说明

How can I print all the actual values ?

You can't mix and match Math, primitive types and BigDecimal like that, if you want real precision, just use BigDecimal only:

BigDecimal value = new BigDecimal(2);
System.out.println(value.pow(1000));

If you want to see the actual value of a double, use the BigDecimal(double) constructor. Double.toString(lnumber) does rounding.

System.out.println(new BigDecimal((Math.pow(2, 1000)))) outputs 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Math.pow(2,1000) is exactly representable in double, because it is a power of two that is in the representable range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM