Help coderanch get a
new server
by contributing to the fundraiser
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
• Ron McLeod
• Paul Clapham
• Devaka Cooray
• Liutauras Vilda
Sheriffs:
• Jeanne Boyarsky
• paul wheaton
• Henry Wong
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Tim Moores
• Carey Brown
• Mikalai Zaikin
Bartenders:
• Lou Hamers
• Piet Souris
• Frits Walraven

# floating point math

Ranch Hand
Posts: 56
• Number of slices to send:
Optional 'thank-you' note:
I would appreciate some help on this topic as I have access to only one compiler...
In Brogden's Mock Exam #28, the explanation of the correct answer hinges on the concept of the imprecise representation of rational fractions in floating point types, to wit: ( ( 1.0F / 3.0F ) * 3.0F ) != 1.0F according to the explanation.
However Brogden's actual question code in the question uses:
( ( 1.0F / 3.0F ) * 3.0 ) == 1.0F
(note the sneaky insertion of a double literal)
Based on some test code examples, the above only evalutates because of the arithmetic promotion of float to double. That is,
( ( 1.0F / 3.0F ) * 3.0D ) == 1.0F evaluates to false but
( ( 1.0F / 3.0F ) * 3.0F ) == 1.0F evaluates to true.
Does anyone else find this behavior or is it something magical that the Mac does (besides the magical things they do already)?
For the code he's written, the correct answer and the answer stated as correct match but the reason seems to hinge on floating point calculations involving type conversions not just floating point calculations.
Test code follows.
Best Regards,
Steve Butcher
exceptionraised@aol.com

Greenhorn
Posts: 11
• Number of slices to send:
Optional 'thank-you' note:
in Java, a flot point number must be suffix a "F" otherwise java will think it is a double. For example, 1.0 is a double,
and 1.0F is a float.
If you have this sentence:
float a = 1.0F/3.0F * 3.0;
java compiler will complain there is no explicit cast, because the result of 1.0F/3.0F has been promoted to be a double

Ranch Hand
Posts: 213
• Number of slices to send:
Optional 'thank-you' note:
Hi Steve,
I'm getting the same behavior on Windows too. This has more to do with widening conversions rather than the imprecise floating point calculations in Java.
float a = 1.0F / 3.0F; // a= 0.33333334
double b = a; // b= 0.3333333432674408 (widening conv)
float c = a*3.0f; // c=1.0
double d = a*3.0; // d=1.00000000298023224
The extra digits which are added as a result of the widening conversion of float to double result in the answer not evaluating to 1.0
Therefore it seems to me that the explanation given in Exam Cram is incorrect (atleast for his given code).

 Don't get me started about those stupid light bulbs.