Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precise Multiplication without floating point arithmetic

How can I get the exact result of a multiplication?

Python tells me that 0.017 * 3 equals 0.051000000000000004. Is there any command to make python print 0.051?

like image 375
Jkev Avatar asked Oct 17 '25 19:10

Jkev


2 Answers

Fractional numeric literals in Python have the type float, which is represented in binary. Use the Decimal type for base 10 arithmetic.

>>> from decimal import Decimal
>>> print(Decimal('0.017') * 3)
0.051
like image 69
Chris Martin Avatar answered Oct 20 '25 08:10

Chris Martin


Assuming you know the expected number of significant digits the operation should output, you can use the built-in rounding function in python (in this case 3).

>>> round(0.017 * 3, 3)
0.051
like image 27
jfbeltran Avatar answered Oct 20 '25 07:10

jfbeltran