Is there a way to align both these values from different languages?

92 views Asked by At

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

3

There are 3 answers

0
Jesper Juhl On

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

0
Jonathan Rosenne On

To expand on Shawn's comment: The C++ reply has 17 digits, the java reply has 16. If you round the 17 digits you will get the same result, as 35 rounds to 4. Double has in fact slightly less than 16 (approximately 52+1 bits times log 2) meaningful digits, so the C++ result is misleadingly precise. You can control the number of digits displayed both in C++ and in Java, but as Shawn said the actual number in the bowels of the computer is the same.

0
Water On

When I get look at the bits from both C++ and Java, they result in:

Java:

4634989787871853517

C++:

4634989787871853517

Which means they are both the same bits. Since they should be following IEEE-754, this means both languages have an identical value. You just see one output be slightly truncated in one language, but the value is not.