Single PrecisionDouble Precision IEEE 754基2浮点值可以表示整数范围,而不会丢失。

给定乘积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);
        }
    }
}

10-08 01:12