Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply doubles in Python with same precision as C++

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)

like image 937
Nicolas Avatar asked Oct 10 '17 07:10

Nicolas


2 Answers

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
like image 82
schnaader Avatar answered Nov 02 '22 00:11

schnaader


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.

like image 21
Sraw Avatar answered Nov 02 '22 00:11

Sraw