指定无穷大来浮动 [英] Assign infinity to float
问题描述
float f [] =>我想要初始化一个float值为infinity,而不使用INFINITY宏。 {
0b01111111100000000000000000000000,// 0x7f800000
0x7f800000 -1,
0x7f800000 -2,
0x7f800000 -64,
0x7f800000 -65
};
印制:
2139095040.000000
2139095040.000000
2139095040.000000
2139095040.000000
2139094912.000000
为什么不是第一个数据无穷大(像 1 / 0.0
),而其他数据只有在最后一个数据才会改变?
0x7f7fffff应该是浮点数最大的值,然后尝试这里 0x7f80000被认为是无穷大。
您的问题的原因是符号:
-
0x7f800000
-
0b01111111100000000000000000000000 < code
这个符号与
int
类型有关,当你将int
分配给float
,这意味着隐式转换 from
int
到float
。在这种情况下,你的两个数字都是十进制的2139095040
,它将被定位为float
type。
为了避免这个问题,你可以在4个字节的精确位位置上赋值。这里有几个例子。
float f;
*(int *)& f = 0x7f800000;
或者您可以使用工会
union u_fi {
float f;
int i;
} fi;
fi.i = 0x7f800000;
但使用这2种解决方案时要小心。如果
int
在第一种情况下超过4个字节,并且在int
是big-endian
。所以这个解决方案是平台相关的,我推荐使用如下所示的宏。
你的问题的另一个解决方案是使用非常大的数字转换为
float
为inf
。为此,您可以使用< math.h> #define _HUGE_ENUF 1e + 300
#define INFINITY((float)(_ HUGE_ENUF * _HUGE_ENUF))
float f = INFINITY;
I'm trying to initialize a float to value infinity, and without using INFINITY macro.
float f[] = { 0b01111111100000000000000000000000, // 0x7f800000 0x7f800000 -1, 0x7f800000 -2, 0x7f800000 -64, 0x7f800000 -65 };
Printed:
2139095040.000000 2139095040.000000 2139095040.000000 2139095040.000000 2139094912.000000
Why isn't the first data infinity (like
1 / 0.0
) and the others don't change until the last data?0x7f7fffff should be the biggest value that a float can be and trying here 0x7f80000 is considered infinity.
解决方案The reason of your problem is notations:
0x7f800000
0b01111111100000000000000000000000
This notations related to
int
type and when you assigningint
tofloat
it meansimplicit conversion
fromint
tofloat
. In this case both of your numbers is2139095040
in decimal and it will be conerted tofloat
type.To avoid this problem you may assign value in exact bit positions of 4 bytes. Here a couple of examples.
float f; *(int*)&f = 0x7f800000;
Or you can use unions
union u_fi { float f; int i; } fi; fi.i = 0x7f800000;
But be careful when use this 2 solutions. It won't work safely when
int
is more than 4 bytes in first case and won't work at all whenint
isbig-endian
. So this solutions are platform dependent and I recommend to use macro like it shown below.Another solution to your problem is to use very large number wich converts to
float
asinf
. For this you can use macro as in<math.h>
#define _HUGE_ENUF 1e+300 #define INFINITY ((float)(_HUGE_ENUF * _HUGE_ENUF)) float f = INFINITY;
这篇关于指定无穷大来浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!