Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes ints, floats and doubles Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ints, floats and doubles" Watch "ints, floats and doubles" New topic

ints, floats and doubles

Ed Lance
Ranch Hand

Joined: Aug 02, 2000
Posts: 38
Would appreciate a brief overview of these primitive data types. When coding I sometimes notice a loss of precision when moving from one to the other (especially int to float).
Fiona Barker

Joined: Jul 23, 2001
Posts: 18
Surely I can answer this without even referring to Java? A floating point number is wider and more precise than an integer. I.e., 1.0005 is not the same as 1. A "double" (64 bit floating point) is wider than a "float" (32 bit floating point) which is wider than an "int" (32 bit integer). Perhaps I'm wrong in assuming this is just a simple application of maths ...
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
You may notice a loss of precision going from int-to-float when you're dealing with large numbers. With small numbers (certainly upto 1-million - probably MUCH beyond that as well, but you get my drift) the numbers should match well.
Why is this? Well, if you're really techie, read on - but beware! I'm writing this turned midnight with no reference books to hand
Consider this: Both int and float are 32 bits. Now, 32 bits can take on 2**32 distinct "values" (that is, 2-raised-to-32nd power - ie. 2 times 2 times 2 ..... 32 times). Therefore, both int and float can only have this number of distinct values as well.
The int type holds these as precise integers upto (plus-or-minus) 2**16.
The float type holds a fantastically wider range of numbers: offhand, let's say from 10**-99 through to 10**99 (positive and negative).
You can't get something for nothing. The float type has a wider range of values, but remember that it can still only hold 2**32 distinct values. That means, if there is a "good" match with integers around zero, there has to be a "worse" match with integers far from zero - ie. BIG numbers.
Consider Paul's rocket mass heater.
subject: ints, floats and doubles
It's not a secret anymore!