简体   繁体   English

.NET double和python float有什么区别?

[英]What is the difference between .NET double and python float?

In C#: 在C#中:

Console.WriteLine(1.2d - 1.0d);

produces 0.2 . 产生0.2 In python 3: 在python 3:

print(1.2 - 1.0)

produces 0.19999999999999996 . 产生0.19999999999999996

My goal is to write fast code in C# that produces the same floating point results as python 3. I'm obviously interested in any and all float arithmetic, not just the example above. 我的目标是用C#编写快速代码,产生与python 3相同的浮点结果。我显然对任何浮点运算都感兴趣,而不仅仅是上面的示例。

What is the most practical way to achieve that? 实现这一目标的最实用方法是什么? Is there a library I can use? 我可以使用图书馆吗?

In addition, I would like to understand, what accounts for this difference. 另外,我想了解是什么导致了这种差异。 Both representations are 64 bit, and both seem to be based on IEEE. 两种表示都是64位的,并且似乎都基于IEEE。 So what is different about these implementations that make them produce different results? 那么,这些实现产生不同结果的实现有何不同?

References: 参考文献:

As Jon Skeet points out in the comments, you need to compare the bit representations. 正如Jon Skeet在评论中指出的那样,您需要比较位表示。 Try this in C#: 在C#中尝试:

Console.WriteLine($"{BitConverter.DoubleToInt64Bits(1.2d - 1.0d):X}");

result: 3FC9999999999998 . 结果: 3FC9999999999998

Now in python 3 (courtesy of this answer ): 现在在python 3中(由这个答案提供 ):

import struct
import binascii
print(binascii.hexlify(struct.pack('>d', (1.2 - 1.0))).decode())

result: 3fc9999999999998 结果: 3fc9999999999998

As you can see, the result is the same. 如您所见,结果是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM