如果两个整数的乘积落在浮点类型的无损范围内,是否会无损?

Will the product of two integers be lossless if it falls within the lossless range of the floating point type?

Single Precision and Double Precision IEEE 754 Base 2 Floating Point Values 可以表示一个整数范围而不会丢失。

给定一个乘积 A = BC,其中 BC 是无损表示为浮点值的整数,如果乘积 A 在数学上落在浮点型的无损范围?

更具体地说,我们是否知道普通的现代处理器是否会确保计算乘积以使整数乘积的行为如上所述?

编辑:为了澄清上面的链接,可以无损地表示的整数范围是双精度的 +-253 和单精度的 +-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);
        }
    }
}