javaunderflow

How to deal with underflow in java?


Here's the issue

double a = 1.0665901062490447E-18;
double b = 1.0;
double c = a+b; // this is 1.0

I need that summed value. What do I do about it?


Solution

  • As I mentioned in my comment, 1.0665901062490447E-18 is a very small value. If you need that much precision, you should be using BigDecimal. Something like,

    double a = 1.0665901062490447E-18, b = 1.0;
    System.out.println(BigDecimal.valueOf(a).add(BigDecimal.valueOf(b)).toPlainString());
    

    Which outputs

    1.0000000000000000010665901062490447
    

    Note that there is a predefined constant BigDecimal.ONE - so the above could also be written

    System.out.println(BigDecimal.valueOf(a).add(BigDecimal.ONE).toPlainString());