• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about floats in Java/in general  RSS feed

 
Petar Stoyanov
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say I have the following 3 situations:

a)

b)

c)

Why is the output wrong by all 3 of them?
in a) the result should be 1, because 1e20/1e-20 is the same as 1/1 and its 1 but java outputs Infinity
in b) the expected result is 1.00000001e8 but java outputs 1.0ef. The same as the float c
in c) the expected result is 1.0000001e38, but it should be 1.1e38
 
Fred Kleinschmidt
Bartender
Posts: 572
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is the output wrong by all 3 of them?
in a) the result should be 1, because 1e20/1e-20 is the same as 1/1 and its 1 but java outputs Infinity
in b) the expected result is 1.00000001e8 but java outputs 1.0ef. The same as the float c
in c) the expected result is 1.0000001e38, but it should be 1.1e38

a) 1e20/1e-20 = 1e40, not 1
    1e20 is not the same as 1, nor is 1e-20 the same as 1.
But the real problem is that floating point numbers have only about a maximum of 6 significant figures.
See  http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
Do not confuse range, accuracy, and significant figures.

Try the same code using double instead of float and see what, if anything, changes. Do you understand why?
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fred, the new version of the floating-point document you posted is here. Your link now points to a page which links to the original and also to what I posted, which the author thinks is better now.
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use floats unless some other code requires them.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!