Loss of precision - int -> float or double

2019-01-06 12:42发布

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?

8条回答
再贱就再见
2楼-- · 2019-01-06 13:40

No, float and double are fixed-length too - they just use their bits differently. Read more about how exactly they work in the Floating-Poing Guide .

Basically, you cannot lose precision when assigning an int to a double, because double has 52 bits of precision, which is enough to hold all int values. But float only has 23 bits of precision, so it cannot exactly represent all int values that are larger than about 2^23.

查看更多
萌系小妹纸
3楼-- · 2019-01-06 13:45

Possibly the clearest explanation I've seen: http://www.ibm.com/developerworks/java/library/j-math2/index.html the ULP or unit of least precision defines the precision available between any two float values. As these values increase the available precision decreases. For example: between 1.0 and 2.0 inclusive there are 8,388,609 floats, between 1,000,000 and 1,000,001 there are 17. At 10,000,000 the ULP is 1.0, so above this value you soon have multiple integeral values mapping to each available float, hence the loss of precision.

查看更多
登录 后发表回答