I have a C++ code and an Octave that both compute the same equation
float x = 1.5f;
float y = pow(x, 6) * 235809835.41f - pow(x, 5) * 2110439254.2f + pow(x, 4) *7869448124.8f - pow(x, 3) * 15648965509.0f + pow(x, 2) * 17503313074.0f - (x)* 10440563329.0f + 2594694745.0f; // result y = 3584
x = 1.5
y = (x ^ 6) * 235809835.41 - (x ^ 5) * 2110439254.2 + (x ^ 4) *7869448124.8 - (x ^ 3) * 15648965509 + (x ^ 2) * 17503313074 - (x)* 10440563329 + 2594694745 // result y = 26
The computed value of y differs in the two cases. C++ computes y to be 3584 and Octave computes y to be 26. What could be the cause for this divergence?
EDIT : Excel produces the same result as Octave, and the result is logical too within the context of the equation. So, something is wrong with the C++ code or compiler.
This appears to be due to the limited precision of the
float type, which is likely causing one of the operations to be effectively discarded because one operand is of a smaller enough magnitude than the other to cause a significant change to the result. (See this extremely contrived example that shows what this might look like.)
If you rewrite the code to use the
double type, which is more precise, then the result is 26.810783, which matches the result I get from evaluating the formula in Maxima.
Further reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic