2

The result of expression: 2.227E-19-1.0+1.0 would be 0.0

How can I get result of 2.227E-19 ?

I have an expression

a-b+1

and

  • a always be a very small number.
  • b might be close to 1.0

HOW to keep accuracy when a very small number operate with a big number ?

x y
  • 21
  • 2
  • What is the problem? What you get? What are the values of `a` and `b`? – Marco Acierno Mar 04 '14 at 19:33
  • `+ (1.0 - b)`. But this is a hair artificial: IEEE double has 16 digits of precision, so the smallest variation between `b` and 1 is greater than the size of `a` -- you essentially have lost all accuracy. – Hot Licks Mar 04 '14 at 20:33

3 Answers3

0

Just use a double to store the result. It has more than enough precision for this calculation.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
  • I don't think that's true, testing it with the given values results in 0 even with double precision. – benedek Mar 04 '14 at 19:45
0

If you know beforehand which operands can be small, you can reorder the operations:

-b + 1 + a

This way, the part before a will be calculated first, and both sides (-b+1 and a) will be roughly of the same magnitude, causing less floating-point problems.

Here's a relevant section of The Java™ Tutorials:

Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right;

benedek
  • 396
  • 1
  • 6
  • The above yields more apparent precision but no more accuracy. – Hot Licks Mar 04 '14 at 20:10
  • I'm not sure what you mean exactly; for the case of `b=1` at least, this approach keeps `a` from being cancelled out, which is the main issue as far as I can see. – benedek Mar 04 '14 at 20:24
  • If `b` would really be `1 - 1.0E-17` if calculated in higher precision, the overall result would be quite different from 2.227E-19. Rearranging the order to produce an apparently more precise result does not produce a more accurate result. – Hot Licks Mar 04 '14 at 20:31
0

Or use BigDecimal with enough scale.