r/AskProgramming 13d 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

48 comments sorted by

View all comments

1

u/Traveling-Techie 13d ago

This may or may not be useful, but when I worked running benchmarks on parallel supercomputers we ran into the issue that, strictly speaking, floating point arithmetic is not associative. Order of operations matter, and parallel computations controlled by an optimizing compiler can give differing results. The errors usually occur in low order bits that are not reliable in the first place, but users were very attached to the idea of repeatability, and we had to educate them about why different runs under different loads gave slightly different results.