• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Floating Confusion

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have a confusion...

The following code snippet prints "true"

float f = 1.0F/3.0F;
System.out.println( (f * 3.0F) == 1.0F );

whereas the following prints "false"

double d = 1.0F/3.0F;
System.out.println( (d * 3.0F) == 1.0F );


How is it possible, the value of 1/3 cannot be precisely stored by either variable type. Then why does double return false?

Am I missing something?

Thanks!
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Remember that an implict conversion to double is taking place.

Consider this code.



The output is

 
Talib Jockey
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks bro..but its kindda wierd!!
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(Not an Advanced question at all)

Testing for equality, with floating point, is almost always wrong. It is an inexact data type, so exact equality test generally does not do what you want.

Therefore you have two mistakes: -
  • using float constants (F suffix) with double type
  • worrying about exact equality tests in floating-point


  • [ September 25, 2006: Message edited by: Peter Chase ]
     
    Don't MAKE me come back there with this tiny ad:
    the value of filler advertising in 2021
    https://coderanch.com/t/730886/filler-advertising
    reply
      Bookmark Topic Watch Topic
    • New Topic