'What is the difference between .NET double and python float?

In C#:

Console.WriteLine(1.2d - 1.0d);

produces 0.2.

In python 3:

print(1.2 - 1.0)

produces 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.

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. So what is different about these implementations that make them produce different results?

References:



Solution 1:[1]

As Jon Skeet points out in the comments, you need to compare the bit representations. Try this in C#:

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

result: 3FC9999999999998.

Now in python 3 (courtesy of this answer):

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

result: 3fc9999999999998

As you can see, the result is the same.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community