Jas*_*out 3 floating-point precision processor floating-accuracy
单精度和双精度IEEE 754 Base 2 浮点值可以无损失地表示整数范围。
给定的产物A = BC,其中,B和C是整数表示无损作为浮点值,是产品A总是无损如果它在数学上的浮点类型的无损范围内?
更具体地说,我们是否知道常见的现代处理器是否会确保计算乘积,以便整数乘积的行为如上所述?
编辑:为了澄清上面的链接,可以无损表示的整数范围在双精度中为 +-2 53,在单精度中为 +-16777216。
编辑:IEEE-754 要求将运算四舍五入到最接近的可表示精度,但我特别想知道现代处理器的行为
对于任何基本运算,IEEE-754 要求,如果数学结果是可表示的,那么它就是结果。
这个问题没有用 IEEE-754 标记,因此一般只询问浮点数。当确切的结果可以表示时,任何明智的系统都不会给出不准确的结果,但仍然可以创建一个。
这是一个测试float案例的程序。
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static void Test(float x, float y, float z)
{
float o = x*y;
if (o == z) return;
printf("Error, %.99g * %.99g != %.99g.\n", x, y, z);
exit(EXIT_FAILURE);
}
static void TestSigns(float x, float y, float z)
{
Test(-x, -y, +z);
Test(-x, +y, -z);
Test(+x, -y, -z);
Test(+x, +y, +z);
}
int main(void)
{
static const int32_t SignificandBits = 24;
static const int32_t Bound = 1 << SignificandBits;
// Test all x * y where x or y is zero.
TestSigns(0, 0, 0);
for (int32_t y = 1; y <= Bound; ++y)
{
TestSigns(0, y, 0);
TestSigns(y, 0, 0);
}
/* Iterate x through all non-zero significands but right-adjusted instead
of left-adjusted (hence making the low bit set, so the odd numbers).
*/
for (int32_t x = 1; x <= Bound; x += 2)
{
/* Iterate y through all non-zero significands such that x * y is
representable. Observe that since x and y each have their low bits
set, x * y has its low bit set. Then, if Bound <= x * y, there is
a also bit set outside the representable significand, so the
product is not representable.
*/
for (int32_t y = 1; (int64_t) x * y < Bound; y += 2)
{
/* Test all pairs of numbers with these significands, but varying
exponents, as long as they are in bounds.
*/
for (int xs = x; xs <= Bound; xs *= 2)
for (int ys = y; ys <= Bound; ys *= 2)
TestSigns(xs, ys, (int64_t) xs * ys);
}
}
}
Run Code Online (Sandbox Code Playgroud)