在下面的代码中从int转换为float时,为什么会有价值损失? [英] Why there is loss of value when converting from int to float in the below code?

查看:77
本文介绍了在下面的代码中从int转换为float时,为什么会有价值损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int value1 = 123456789;
float value2 = value1;
System.out.println(value1);
System.out.println(value2);

输出:

123456789
123456792

123456789
123456792

推荐答案

float 类型使用与 int 相同的位数(32位)来表示浮点数比 int 更大的范围内的数字仅用于表示整数.

The float type uses the same number of bits as int (32 bits) to represent floating point numbers in the larger range than int uses to represent only integers.

这会导致精度下降,因为并非每个 int 编号都可以用 float 准确表示.仅24位用于表示数字的小数部分(包括符号位),而其他8位用于表示指数.

This causes a loss of precision, since not every int number can be represented accurately by a float. Only 24 bits are used to represent the fraction part of the number (including the sign bit), while the other 8 are used to represent the exponent.

如果将此 int 值分配给 double ,则不会造成任何精度损失,因为 double 具有64位,其中超过32个用于表示分数.

If you assign this int value to a double, there won't be any loss of precision, since double has 64 bits, and more than 32 of them are used to represent the fraction.

这是更详细的说明:

123456789作为int的二进制表示形式是:

The binary representation of 123456789 as an int is :

00000111 01011011 11001101 0001 0101

使用以下公式,从其32位中构造一个单精度浮点数:

(-1)^sign * 1.b22 b21 ... b0 * 2^(e-127)

其中 sign 是最左边的位(b31).b22到b0是分数位,而b30到b23位组成指数e.

Where sign is the left most bit (b31). b22 to b0 are the fraction bits, and bits b30 to b23 make the exponent e.

因此,将 int 123456789转换为 float 时,只能使用以下25位:

Therefore, when you convert the int 123456789 to float, you can only use the following 25 bits :

00000111 01011011 11001101 00010101
-    --- -------- -------- -----

我们可以安全地摆脱任何前导零(除符号位之外)和任何尾随零.这给您留下了3个最低有效位,我们必须将其删除.我们可以减去5得到123456784:

We can safely get rid of any leading zeroes (except of the sign bit) and any trailing zeroes. This leaves you with the 3 least significant bits, which we must drop. We can either subtract 5 to get 123456784:

00000111 01011011 11001101 00010000
-    --- -------- -------- -----

或加3以获得123456792:

or add 3 to get 123456792:

00000111 01011011 11001101 00011000
-    --- -------- -------- -----

显然加3可以得到更好的近似值.

Obviously adding 3 gives a better approximation.

这篇关于在下面的代码中从int转换为float时,为什么会有价值损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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