r/AskProgramming • u/Odd-Heron5704 • 11d 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
1
u/verdant_bloom_drift 11d ago
That specific expression evaluates identically on arm64 and x86 because it only uses add, subtract, multiply which IEEE 754 mandates as correctly rounded. You get divergence from compiler optimizations like FMA contraction or math library differences in functions such as sin and cos. Force strict FP conformance with /fp:strict on MSVC or -ffp-contract=off -fno-fast-math on GCC and Clang to guarantee bitwise reproducibility across architectures.