• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Floating-point Operations

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q2.
What happens on trying to compile and run the following code?
1.public class EqualsTest{
2.public static void main( String args[] ){
3.float A = 1.0F / 3.0F ;
4.if( ( A * 3.0F) == 1.0F )
5.System.out.println( "Equal" );
6.else
7.System.out.println( "Not Equal" );
8. }
9. }

A)The program compiles and prints "Not Equal".
B)The program compiles and prints "Equal".
C)The compiler objects to line 3.
D)The compiler objects to using == with primitives in line 4.
The answer mentioned is (a).Should'nt it be (b) ???
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey, I recognize that question. <grin/>
That was a badly chosen example to demonstrate the danger of exact comparison when doing floating point math. Like it says on the errata page (www.lanw.com/books/errata), you should:
change
4. if( ( A * 3.0F) == 1.0F )
to
4. if( ( A * 3.0) == 1.0F )
and then try the code.
Incidently, I do respond to email, so if you have questions about anything in the books, write!
wbrogden@lanw.com
Bill

------------------
author of:
 
reply
    Bookmark Topic Watch Topic
  • New Topic