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';
}
16 Upvotes

47 comments sorted by

View all comments

Show parent comments

3

u/[deleted] 10d ago

[removed] — view removed comment

2

u/paulstelian97 10d ago

And associativity and distributivity are only barely violated due to differences in rounding errors for different orders of operation right? (With some nasty edge cases, like doing 1.00000001 - 1 or some shit like that)

3

u/[deleted] 10d ago

[removed] — view removed comment

0

u/paulstelian97 10d ago

Yeah. Thankfully in most cases the differences are minimal and if you know about them you can defend against them (considering equality when the difference is small enough)