Search code examples
c++floating-pointprecisionfloating-accuracyfloating-point-conversion

Will different math CPUs yield the same floating point results?


I'm developing on OS portable software that has unit tests that must work on Linux, UNIX, and Windows.

Imagine this unit test that asserts that the IEEE single-precision floating point value 1.26743237e+015f is converted to a string:

void DataTypeConvertion_Test::TestToFloatWide()
{
    CDataTypeConversion<wchar_t> dataTypeConvertion;
    float val = 1.26743237e+015f;
    wchar_t *valStr = (wchar_t*)dataTypeConvertion.ToFloat(val);
    std::wcout << valStr << std::endl;
    int result = wcscmp(L"1.26743E+015", valStr);
    CPPUNIT_ASSERT_EQUAL(0, result);
    delete [] valStr;
}

My question is: Will all OS and processors convert the float to the string "1.26743E+015" as long as the float is a IEEE? I'm asking since I know the math CPUs may not return accurate results, and I was wondering if that would yield different results on different processors as they may have different hardware implementations of IEEE floating point operations internally inside the processor architecture.


Solution

  • The answer, sadly, is most likely to be no. Conversion of a floating point number to and from arbitrary strings is not guaranteed across platforms.

    In principle at least, all processors you are likely to come across conform to the IEEE 754 standard. The standard is reasonably tight, to the extent that it defines floating point arithmetic. You can add/subtract/multiple or divide floating point numbers with a reasonable expectation of getting identical results across platforms at the bit level.

    The standard also defines conversion to and from a 'character representation'. In principle that requires complying implementations to be compatible but it has 'wiggle room'. Not all numbers have to produce identical results.

    You should also be aware that the default precision and format may vary across platforms.

    Having said all that, you may be able to achieve your desired results as long as (a) you control the width and precision of strings rather than leaving it to default (b) you choose a precision that is well within the maximum available for the particular format (c) avoid NaN and similar.

    The article here is quite helpful.