0

I've just been learning about floating point numbers and am having difficulty understanding how I am supposed to find 3 double values (let's say a, b, and c) so that:

(a + b) + c == 1.0 and a + (b + c) == 0.0

I've read several web pages and watched videos about what floating points are but I have no idea how I should find something like this. I tried different numbers but only get much smaller differences in my outcomes. e.g.

(1.1 - 0.2) + 0.1 = 1.0000000000000002

1.1 +(-0.2 + 0.1) = 1.0

  • 1
    See here: http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Johannes Jander Mar 01 '16 at 18:01
  • You should be aiming for things that are 0 and not-quite 0. For example, `(1.1 - 0.2) - 0.9`. Now, what happens if you make all the numbers bigger? – Rex Kerr Mar 01 '16 at 18:03
  • A key idea for this is that the gap between adjacent floats increases with magnitude. It can be so large that adding 1 to a number does not change its value, because the original number is the closest representable number to the exact result. – Patricia Shanahan Mar 01 '16 at 18:36
  • 1
    Thank you! I figured it out by using a huge number for a and b and a small one for c. – mangopancake Mar 01 '16 at 18:56

1 Answers1

-1

In the general case, you can only compare the results of floating operations with respect to an error margin you trust.

For example, using the Scalactic library:

import orc.scalactic.TripleEquals._
import orc.scalactic.Tolerance._

(1.1 -   0.2) + 0.1  === 1.0 +- 1.0e-6  // true
 1.1 + (-0.2  + 0.1) === 1.0 +- 1.0e-6  // true

If you don't want this, you need to use BigDecimal precise maths.

0__
  • 66,707
  • 21
  • 171
  • 266