Having issues with the sqrt function in two languages.
I have a JAVA API and C++ client, I'm trying to use the sqrt functions in both but they give me slightly different numbers.
The inputs are:
x = 25.0
y = 5625.0
Java:
double distance = Math.sqrt(x + y);
// outputs 75.16648189186454
C++:
const double distance = std::sqrt(x + y);
// outputs 75.166481891864535
I need the numbers to be the same as I'm using them as seeds in the API and client. Is there any way to do this? Ideally the java output 75.16648189186454, however, I will take either.
Many thanks
Floating point numbers are not exact and you cannot depend on different implementations (languages) getting the exact same value. Nor can you rely on the same language getting the same value on different hardware.
Serialising floating point numbers and transmitting them between different languages and/or hardware implentations is a hard (not N/P hard, but still really difficult) problem.
I'd recommend reading these links for in-depth details:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Is floating point math broken?
Sometimes Floating Point Math is Perfect