[英]Is there a way to align both these values from different languages?
Having issues with the sqrt function in two languages. sqrt函数有两种语言存在问题。
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. 我有一个JAVA API和C ++客户端,我试图同时使用sqrt
函数,但是它们给我的数字略有不同。
The inputs are: 输入是:
x = 25.0
y = 5625.0
Java: Java的:
double distance = Math.sqrt(x + y);
// outputs 75.16648189186454
C++: 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. 我需要数字与在API和客户端中将其用作种子时使用的数字相同。 Is there any way to do this? 有什么办法吗? Ideally the java
output 75.16648189186454
, however, I will take either. 理想情况下, java
输出75.16648189186454
,但是我还是选择其中一个。
Many thanks 非常感谢
When I get look at the bits from both C++ and Java, they result in: 当我看一下C ++和Java的代码时,它们会导致:
Java: Java的:
4634989787871853517
C++: 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. 由于它们应遵循IEEE-754,因此这两种语言的值相同。 You just see one output be slightly truncated in one language, but the value is not. 您只看到一种输出在一种语言中被略微截断了,但是值却没有。
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. 序列化浮点数并在不同的语言和/或硬件要求之间传输它们是一个难题 (不是N / P难题,但仍然非常困难 )。
I'd recommend reading these links for in-depth details: 我建议阅读以下链接以获取详细信息:
What Every Computer Scientist Should Know About Floating-Point Arithmetic 每个计算机科学家都应了解的浮点运算法则
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. 扩展Shawn的评论:C ++答复有17位数字,Java答复有16位数字。如果将17位数字四舍五入,您将得到相同的结果,即35位四舍五入。Double实际上略小于16(大约52+ 1位乘以2)记录有意义的数字,因此C ++结果具有误导性。 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. 您可以控制C ++和Java中显示的数字位数,但是正如Shawn所说,计算机肠道中的实际数字是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.