Loss of precision - int -> float or double

后端 未结 9 1457
小蘑菇
小蘑菇 2020-11-27 15:22

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

相关标签:
9条回答
  • 2020-11-27 16:08

    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

    0 讨论(0)
  • 2020-11-27 16:12

    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.

    0 讨论(0)
  • 2020-11-27 16:14

    There are two reasons that assigning an int to a double or a float might lose precision:

    • There are certain numbers that just can't be represented as a double/float, so they end up approximated
    • Large integer numbers may contain too much precision in the lease-significant digits
    0 讨论(0)
提交回复
热议问题