Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

Guoqiao Sun
Ranch Hand

Joined: Jul 18, 2001
Posts: 317
Dear all, plz see the following code and give me some explanation:

The o/p is:

The question is, why long value results in equal but int value results in not equal.
Guoqiao

Guoqiao Sun<br />SCJP2 SCWCD2<br />Creator of <a href="http://www.jiris.com/" target="_blank" rel="nofollow">www.jiris.com</a>, Java resource, mock exam, forum
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12569

1
The int to float loses some bits of precision.
You are comparing two double values arrived at by different conversion paths.
int -> -> double
int -> float -> double
Since float uses 32 bits, it uses some for the exponent and has fewer bits for precision.
Bill

Java Resources at www.wbrogden.com
Gagan Indus
Ranch Hand

Joined: Feb 28, 2001
Posts: 346
I hav a q about William's explanation
applyiong the same logic ,
we shld get "Not equal " for first call to compare
becoz conversion paths r
Long -> Double
Long -> float -> Double

long is 64 bit ? wont more bits be lost while converting to float's base-mantisaa format ??
------------------
Gagan (/^_^\)

Gagan (/^_^\) SCJP2 SCWCD IBM486 <br />Die-hard JavaMonk -- little Java a day, keeps you going.<br /><a href="http://www.objectfirst.com/blog" target="_blank" rel="nofollow">My Blog</a>
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
It has to do with rounding that occurs under IEEE float rules.
Copy f to a double (g) and print both:
f = 2.14748365E9
g = 2.147483648E9
------------------
Tom - SCJP --- Co-Moderator of the Programmer Certification Forums

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Guoqiao Sun
Ranch Hand

Joined: Jul 18, 2001
Posts: 317
I am still not very clear.
Guoqiao

It is sorta covered in the JavaRanch Style Guide.