Page 1 of 1
About Question com.enthuware.ets.scjp.v6.2.227 :
Posted: Sun Sep 18, 2011 3:41 am
by Andrei Test
Quote from the explanation :
Note that. actually 1/3 is .33333333..... but it shows f as .33...4, So f*3 is 1.00...X (a little more than one.) but it is too precise to be represented by a float so we get 1.0. So, finally the code prints true. Had f been a double, it would have printed false.
So why the expected result is false ?
I checked it in the code, it prints true and I selected "true" as a correct response, but the application says that I am wrong.
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
Posted: Sun Sep 18, 2011 11:21 am
by admin
That's because the question says it will print false. You need to read the question very carefully.
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
Posted: Sun Sep 18, 2011 12:26 pm
by Andrei Test
Another tricky question...
Thank you very much
![Wink ;)](./images/smilies/icon_e_wink.gif)
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
Posted: Tue Oct 18, 2011 9:08 am
by Bartosz JagodziĆski
You state in the explanation that:
Had f been a double, it would have printed false.
Which is confiusing because only if you modify the code like this:
Code: Select all
double f = 1.0f/3.0f;
System.out.println( (f * 3.0f) == 1.0f );
it prints false...
Any other modifications end up printing true. Please clarify the explanation.
Cheers from Poland!
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
Posted: Tue Oct 18, 2011 9:24 am
by admin
Hello,
The problem is with double f = 1.0f/3.0f;
For f to get the high resolution double value, the expression on the right hand side must evaluate to a high resolution double value. However, when you do 1.0f/3.0f, you are forcing the RHS to perform float division and then promote the resulting float (which has already lost the high resolution), to double. So the variable f only gets a less precise double value.
For the RHS to perform double computation, at least one operand should be a double. So 1.0/3.0f or 1.0f/3.0 will print true.
HTH,
Paul.