Java中的信息流失从长久到浮动 [英] information loss from long to float in Java

查看:54
本文介绍了Java中的信息流失从长久到浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您调用以下Java方法

if you call the following method of Java

void processIt(long a) {
  float b = a;  /*do I have loss here*/
}

将long变量分配给float变量时会丢失信息吗?

do I have information loss when I assign the long variable to the float variable?

Java语言规范说 float 类型是 long 的超类型.

The Java language Specification says that the float type is a supertype of long.

推荐答案

是的,这是可能的:如果仅出于 float 的有效位数太少(通常为6-7)的原因而无法处理以及 long 可以代表的所有可能数字(19个有效数字).部分原因是 float 仅具有32位存储,而 long 具有64位(另一部分是float的存储格式).按照JLS的 :

Yes, this is possible: if only for the reason that float has too few (typically 6-7) significant digits to deal with all possible numbers that long can represent (19 significant digits). This is in part due to the fact that float has only 32 bits of storage, and long has 64 (the other part is float's storage format ). As per the JLS:

将int或long值转换为float或将long值转换为double的加宽转换,可能会导致精度降低-也就是说,结果可能会丢失一些最低有效位值的位.在这种情况下,使用IEEE 754舍入到最近模式(第4.2.4节),结果浮点值将是整数值的正确舍入版本.

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).

例如:

long i = 1000000001; // 10 significant digits
float f = i;
System.out.printf(" %d %n %.1f", i, f);

此打印(突出显示差异):

This prints (with the difference highlighted):

 1000000001
 1000000000.0
          ~  ← lost the number 1

值得注意的是,将 int 浮动为 float ,将 long 更改为 double 的情况也是如此(例如根据该报价).实际上,唯一不会丢失精度的整数→浮点转换是 int double .

It is worth noting this is also the case with int to float and long to double (as per that quote). In fact the only integer → floating point conversion that won't lose precision is int to double.

~~~~~~

我会说部分,因为对于 int 加宽到 float 也是如此,这也会丢失尽管 int float 都具有32位,但仍具有精度.上面相同的示例,但带有 int i 的结果与打印的结果相同.一旦考虑了 float 的结构方式,这就不足为奇了.它使用某些32位存储尾数或有效位数,因此不能表示与 int 处于同一范围内的所有整数.

I say in part as this is also true for int widening to float which can also lose precision, despite both int and float having 32-bits. The same sample above but with int i has the same result as printed. This is unsurprising once you consider the way that float is structured; it uses some of the 32-bits to store the mantissa, or significand, so cannot represent all integer numbers in the same range as that of int.

这篇关于Java中的信息流失从长久到浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆