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.
About Question com.enthuware.ets.scjp.v6.2.227 :
Moderator: admin
-
- Site Admin
- Posts: 10065
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
That's because the question says it will print false. You need to read the question very carefully.
If you like our products and services, please help us by posting your review here.
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
Another tricky question...
Thank you very much
Thank you very much
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
You state in the explanation that:
it prints false...
Any other modifications end up printing true. Please clarify the explanation.
Cheers from Poland!
Which is confiusing because only if you modify the code like this:Had f been a double, it would have printed false.
Code: Select all
double f = 1.0f/3.0f;
System.out.println( (f * 3.0f) == 1.0f );
Any other modifications end up printing true. Please clarify the explanation.
Cheers from Poland!
-
- Site Admin
- Posts: 10065
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.227 :
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.
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.
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 113 guests