-4

int big = 1234567890; float approx = big; System.out.println(big - (int)approx);

The system prints out -46. I thought that float only allows for 7 significant figures meaning the operation would be 1234567890-1234567=1,233,333,323. How is it possible for it to print -46?

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Joe C Mar 08 '18 at 22:12
  • Possible duplicate of [sign changes when going from int to float and back](https://stackoverflow.com/questions/20453449/sign-changes-when-going-from-int-to-float-and-back) – abbath Mar 08 '18 at 22:16
  • 3
    Not a duplicate of both proposals. The OP does not understand why 1234567 is not the closest approximation of 1234567890. That has nothing to do with anything at all. – Andrey Tyukin Mar 08 '18 at 22:32
  • 2
    http://idownvotedbecau.se/noresearch/, e.g. printing the value of `approx`, which would instantly have highlighted your misconception of what "7 significant figures" means. I mean, if the code prints `-46` when you expect `1233333323` from a simple subtraction operation, the very first thought should be that the two values of the subtraction are not what you think they are, and printing them would be the next step in **RESEARCHING** the issue by yourself. – Andreas Mar 08 '18 at 22:52
  • https://xkcd.com/1159/ – Andrey Tyukin Apr 25 '18 at 15:12

1 Answers1

2

I think there is a problem with the interpretation of the phrase "significant figure"?

Whether you have

1234567890 US-dollars

or

1234567936 US-dollars

is not that significant of a difference.

But if you instead had

   1234567 US-dollars

that would be a very significant difference.

1234567890
^       ^
|        \
|         less significant
|
very significant

Thus, an approximation of

1234567890

to 7 decimal significant figures is something between (approximately)

1234567390

and (approximately)

1234568390

In this case, it turns out to be roughly

1234567936
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93