问题描述
我试图弄清楚如何将负无穷大的值分配给float或double变量。似乎包括标准库限制在内,我可以获得无穷大表示形式,而且我(肯定)知道在该无穷大表示形式(无穷大)之前加上减号可能会导致我在IEEE754浮点中寻找的值标准(因为0x7FFFFFFF可能会在0xFFFFFFFF上产生),但是我什至对此不确定,更不用说可能存在的其他标准(如果有的话)。我发现它确实非常不专业且依赖于实现。
I'm trying to figure out how to assign the value of negative infinity to a float or double variable. It seems that including the standard library limits, I can get the infinity representation, and I know (quite surely) that adding a minus in front of that (-infinity) might result in the value I'm looking for in the IEEE754 floating point standard (as 0x7FFFFFFF might result on 0xFFFFFFFF), but I'm not even sure about that, not to mention other standards that might be out there (If there are any). I find it really, really unprofessional and implementation dependant.
是否有一种很好的方法可以独立地获得负无穷大平台和实现的价值,否则,我可能只是以及使用#define,每个人都喜欢预处理。
Is there a good way to get the value of negative infinity platform and implementation independently, of course, otherwise I might just as well use a #define, everybody likes preprocessing.
推荐答案
至少在(IEEE 754)为true(这可以保证也是正确的),您可以用正负无穷大的方式表示
At least if std::numeric_limits::is_iec559 (IEEE 754) is true (which guarantees, that std::numeric_limits::has_infinity is also true), you can express positive and negative infinity values the way you already stated.
对:
Short explanation of IEEE 754-1985 infinity values from Wikipedia:
有偏见-exponent字段全为1,表示
无穷大或无效的计算结果。
The biased-exponent field is filled with all 1 bits to indicate eitherinfinity or an invalid result of a computation.
正无穷大
正无穷大表示如下:
sign = 0 for positive infinity, 1 for negative infinity.
biased exponent = all 1 bits.
fraction = all 0 bits.
......剪裁......
......snip......
断言
以下示例将按预期运行,或者在目标平台不支持IEEE的情况下导致编译时错误
The following example will either work as expected, or cause a compile time error in case the target platform does not support IEEE 754 floats.
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <limits>
int main(void)
{
//Asserts floating point compatibility at compile time
static_assert(std::numeric_limits<float>::is_iec559, "IEEE 754 required");
//C99
float negative_infinity1 = -INFINITY;
float negative_infinity2 = -1 * INFINITY;
float negative_infinity3 = -std::numeric_limits<float>::infinity();
float negative_infinity4 = -1 * std::numeric_limits<float>::infinity();
assert(std::isinf(negative_infinity1) && negative_infinity1 < std::numeric_limits<float>::lowest());
assert(std::isinf(negative_infinity2) && negative_infinity2 < std::numeric_limits<float>::lowest());
assert(std::isinf(negative_infinity3) && negative_infinity3 < std::numeric_limits<float>::lowest());
assert(std::isinf(negative_infinity4) && negative_infinity4 < std::numeric_limits<float>::lowest());
return EXIT_SUCCESS;
}
这篇关于负无穷大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!