浮点后的浮点数位布局如何给我某些值? [英] How does the bit layout of the floats give me certain values after bit shifting?

查看:74
本文介绍了浮点后的浮点数位布局如何给我某些值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇并想了解有关浮点的更多信息,我运行了以下C代码:

Out of curiosity and wanting to learn more about floating point, I ran the following C code:

#include <stdio.h>

int main() {
  float a = 1.0 + ((float) (1 << 22));
  float b = 1.0 + ((float) (1 << 23));
  float c = 1.0 + ((float) (1 << 24));

  printf("a = %.6f\n", a);
  printf("b = %.6f\n", b);
  printf("c = %.6f", c);
}

结果是:

a = 4194305.000000
b = 8388609.000000
c = 16777216.000000

我对为什么得到这些结果感到困惑.谁能解释为什么a,b和c的位布局导致每个值都是原来的值?我是位偏移和浮动的新手,对它的清晰解释将不胜感激.谢谢.

I'm confused on why I got these results. Can anyone explain why the bit layout of a, b, and c causes each value to be what it is? I'm new to bit shifting and floats and a clear explanation would be greatly appreciated. Thank you.

推荐答案

(1 << 22)

是一个等于

2^22 = 4194304

然后通过执行(float)(1<<<<<< 22)将其转换为float值

then you convert it to float by doing (float) (1 << 22) which gives you the same value

4194304.0

然后添加1.0以得到结果4194305.0

and then you add 1.0 to get the result 4194305.0

其他情况也是如此.

因此,这与花车的布局"无关.-而是关于整数的布局以及从整数到浮点的转换.

So this is not about "layout of floats" - it's rather about layout of integers and conversion from integer to float.

但是,最后一种情况是您使用 1<<24 有点有趣(与浮点格式有关).

However, the last case where you use 1 << 24 is a bit interesting (and relates to float format).

(1 << 24) is 16777216

并可以转换为相同的浮点值,即

and can be converted to the same float value, i.e.

16777216.0

但是当你这样做

1.0 + 16777216.0

你仍然得到

16777216.0

原因是浮点数的精度有限(即,并非所有数字都可以浮点数格式显示).值16777217.0无法以浮点格式显示,因此在16777216.0中添加1.0仍会得到16777216.0

The reason is the limited precision of floats (i.e. not all numbers can be presented in the float format). The value 16777217.0 can't be presented in the float format so adding 1.0 to 16777216.0 still gives you 16777216.0

顺便说一句:舍入模式有几种(请参见例如 https://en.wikipedia.org/wiki/Floating-point_arithmetic#Rounding_modes ),因此当无法以浮点格式显示精确结果时,您需要了解系统的舍入模式,以找出将使用哪个值代替精确值结果.

BTW: There are several rounding modes (see e.g. https://en.wikipedia.org/wiki/Floating-point_arithmetic#Rounding_modes) so when an exact result can't be presented in the float format, you need to know your systems rounding mode to figure out which value will be used instead of the exact result.

这篇关于浮点后的浮点数位布局如何给我某些值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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