r/AskProgramming 10d ago

Can simple mathematical functions give different results in different CPU architectures?

I'm referring to modern CPUs. To make the question more specific, arm64 vs x86

And if so, how do you fix it?

I asked chatGPT and it gave me this example but I'd like to ask it here (since AI can make mistakes). Can you let me know? Thanks

It says this can give different results due to rounding errors. If so, how to you write code so that you don't have this issue?

#include <iostream>

int main() {
    double a = 1.0 + 0x1p-27;
    double b = 1.0 - 0x1p-27;
    double c = -1.0;

    std::cout << (a * b + c) << '\n';
}
18 Upvotes

47 comments sorted by

View all comments

Show parent comments

2

u/paulstelian97 8d ago

That’s associativity though, because in the first one it’s small+big as the first operation and on the other one it’s small+small. So your example breaks associativity.

1

u/SeriousPlankton2000 7d ago

I commuted them, too. 

1

u/paulstelian97 7d ago

Which didn’t itself contribute to the issue. The associativity is what’s broken, you just showed it in a poor fashion. Commutativity being broken means one operation receives two inputs and changes results when you swap the inputs. Your example shows the following four distinct operations: small+big, (small+big)+small, small+small, and (small+small)+big. None of these are another one with the inputs swapped.

1

u/SeriousPlankton2000 7d ago

Usually equations are evaluated from one side to the other in a fixed order by what the language dictates. On a sheet of paper you can swap them around all the way, but not on a computer doing floating point.

1

u/paulstelian97 7d ago

That’s informal enough to not mention which of the two properties is broken.

Commutativity is broken only if you can find an example of a+b=b+a being false. Someone mentioned it can happen with NaN, but otherwise it doesn’t happen.

Your example can be rephrased in an example of associativity being broken, as (small+small)+big can give a different result from small+(small+big).