KJS*_*KJS 3 c++ floating-point floating-accuracy
例如:
float a = 3.14159f;
Run Code Online (Sandbox Code Playgroud)
如果我要检查这个数字中的位(或任何其他标准化的浮点数),那么在某些其他平台/编译器组合中这些位的可能性有多大,或者可能?
您的问题可以改为:以下代码中的最终断言是否始终得到维护,无论您在哪个平台上运行它?
#include <cassert>
#include <cstring>
#include <cstdint>
#include <limits>
#if __cplusplus < 201103L // no static_assert prior to C++11
#define static_assert(a,b) assert(a)
#endif
int main() {
float f = 3.14159f;
std::uint32_t i = 0x40490fd0;// IEC 659/IEEE 754 representation
static_assert(std::numeric_limits<float>::is_iec559, "floating point must be IEEE 754");
static_assert(sizeof(f) == sizeof(i), "float must be 32 bits wide");
assert(std::memcmp(&f, &i, sizeof(f)) == 0);
}
Run Code Online (Sandbox Code Playgroud)
答:C++标准中没有任何内容可以保证断言得到维护.然而,在大多数理智的平台上,无论平台是大端还是小端,断言都会成立并且代码不会中止.只要您只关心您的代码在某些已知的平台上工作,它就可以了:您可以验证测试是否通过那里:)
实际上,一些编译器可能会使用一个小数到十进制到IEEE-754的转换例程,它不能正确地舍入结果,所以如果你指定f
了足够的精度数字,那么它可能是一些LSB的尾数.最接近十进制表示的值.然后断言将不再存在.对于这样的平台,您可能希望测试所需的几个尾数LSB.
归档时间: |
|
查看次数: |
121 次 |
最近记录: |