Java loss of precision

前端 未结 3 407
盖世英雄少女心
盖世英雄少女心 2020-12-12 05:04

I have a problem concerned with losing of precision

my task is to print numbers as strings

int exponent = ...
int[] Mantissas = { 1, 2, 5 };
double          


        
相关标签:
3条回答
  • 2020-12-12 05:25

    As mentioned by others you have to use java.math.BigDecimal instead of float/double. This however comes with its own set of problems.

    For instance when you call BigDecimal(double) the value you pass in will be expanded to its full representation:

    BigDecimal oneTenth = new BigDecimal(0.1);
    BigDecimal oneMillion = new BigDecimal(1000000);
    oneTenth.multiply(oneMillion)
    out> 100000.0000000000055511151231257827021181583404541015625000000
    

    But when you use the BigDecimal(String) constructor the eact value is represented and you get

    BigDecimal oneTenth = new BigDecimal("0.1");
    BigDecimalr oneMillion = new BigDecimal(1000000);
    oneTenth.multiply(oneMillion)
    out> 100000.0
    

    You can read more on BigDecimal's limitations in Joshua Bloch and Neal Gafter's splendid Java puzzlers book and in this informative article. Finally note that toString on BigDecimal's will print in scientific notation so you will properly have to use toPlainString instead.

    0 讨论(0)
  • 2020-12-12 05:27

    The double type does not have infinite precision and cannot represent decimals exactly. You are observing normal rounding errors. For arbitrary precision arithmetic, you will need to use java.math.BigDecimal instead.

    0 讨论(0)
  • 2020-12-12 05:36

    Search for "floating point numbers" on SO and you'll get a slew of answers as to why this happens. It has to do with how floating point numbers are represented in computers.

    How is floating point stored? When does it matter?

    Another article on the matter - Floating Point Approximation

    0 讨论(0)
提交回复
热议问题