Loss of precision - int -> float or double

stan picture stan · May 6, 2010 · Viewed 39.9k times · Source

I have an exam question I am revising for and the question is for 4 marks.

"In java we can assign a int to a double or a float". Will this ever lose information and why?

I have put that because ints are normally of fixed length or size - the precision for storing data is finite, where storing information in floating point can be infinite, essentially we lose information because of this

Now I am a little sketchy as to whether or not I am hitting the right areas here. I very sure it will lose precision but I can't exactly put my finger on why. Can I get some help, please?

Answer

Dead account picture Dead account · May 6, 2010

In Java Integer uses 32 bits to represent its value.

In Java a FLOAT uses a 23 bit mantissa, so integers greater than 2^23 will have their least significant bits truncated. For example 33554435 (or 0x200003) will be truncated to around 33554432 +/- 4

In Java a DOUBLE uses a 52 bit mantissa, so will be able to represent a 32bit integer without lost of data.

See also "Floating Point" on wikipedia