I am rewriting a C++ program into Python. I need to multiply 2 doubles but C++ and Python don't give the same result. Here's an example with 'hard-coded' values:
C++
printf("%f", ( 44474025505478620106407223274000875520.0 * 5454277033526873088.0 ) );
>>> 242573655903020442240866171189072992939998568974355791872.0
Python
print("%f" % ( 44474025505478620106407223274000875520.0 * 5454277033526873088.0 ) )
>>> 242573655903020398684723205308949669628048817708024725504.0
My problem is that I don't need the most accurate result: I need to get (with Python) a result as close as C++'s result as possible.
In my example, the 15 first digits are the same:
C++ > 242573655903020[442240866171189072992939998568974355791872.0
Py > 242573655903020[398684723205308949669628048817708024725504.0
I need to have a result even more close (18 first digits would be nice)
I'm really stuck here... Anybody has an idea?
FYI:
Python version: 2.7.8
C++ compiler: cl.exe (the one from visual studio)
It seems to depend on the Python implementation. For example, with ideone (cpython 2.7.13), I'll get the same result as your C result.
C version on Ideone - Result:
242573655903020442240866171189072992939998568974355791872.000000
Python version on Ideone - Result:
242573655903020442240866171189072992939998568974355791872.000000
Use library decimal
, take your snippet as an example:
from decimal import Decimal
print("%f" % ( Decimal("44474025505478620106407223274000875520.0") * Decimal("5454277033526873088.0") ) )
It gives 242573655903020442240866171189072992939998568974355791872.000000
which is exactly the same as the result given in C
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With