Java Why is converting a long (64) to float (32) considered widening?

白昼怎懂夜的黑 提交于 2019-12-02 17:43:23

The range of values that can be represented by a float or double is much larger than the range that can be represented by a long. Although one might lose significant digits when converting from a long to a float, it is still a "widening" operation because the range is wider.

From the Java Language Specification, §5.1.2:

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

Note that a double can exactly represent every possible int value.

It's considered widening because float and double can represent larger values than long. You may lose precision, but it will be possible to represent the value (at least approximately).

It is considered widening because the numbers that can be represented by a float is larger than numbers that can represented by long. Just because float uses 32 bit precision does not mean the numbers it can represent are limited to 2^32.

For instance the float (float)Long.MAX_VALUE+(float)Long.MAX_VALUE is larger than Long.MAX_VALUE, even though the float has less precision that the long.

If you look at the matter in simple terms, it is about how data has been represented by original designers.

ideally bit depth of long(64) is larger than float(32). But float data has represented using scientific notion which allows to represent considerably much larger range

Ex: 300[original number] : 3×102 [scientific representation]


Long : -2^63 to 2^63-1

Float : (-3.4)*10^38 to (3.4)*10^38

Notice the Long(power of two) Vs Float(power of ten) representational difference here which allow float to have higher range

hope this is helpful

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!