user9837138
user9837138

Reputation:

Float multiplication give Wrong Answer (python)

we know that multiplication and division are inverse each other, so in python Suppose i have a number 454546456756765675454.00 and i want to divided the number with 32 lets define a variable for example

value = 454546456756765675454.00/32

so the output will be, 1.4204576773648927e+19 or 14204576773648926720.000000, now i want to multiply the output with 32 so if i multiply 14204576773648926720.000000 * 32 then the output give me 454546456756765655040.00 not 454546456756765675454.00 why this happend? i am not good at math, but my question is why float multiply give me wrong answer ( i also try decimal module but its not work for me or maybe i dont know how to use decimal module to get exact answer)

Upvotes: 1

Views: 3861

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26175

Within wide range limits, multiplication and division by powers of two, including 32, are exact in binary floating point. Conversion of a decimal is inexact. 454546456756765655040 is the closest IEEE 754 64-bit binary number to 454546456756765675454. The division and multiplication by 32 made no difference.

More generally, division and multiplication by the same number can result in rounding error in finite width decimal/binary etc. fractions unless all the prime factors of the divisor are also prime factors of the radix being used to represent fractions. In both binary and decimal fractions, division and multiplication by 3 can cause rounding error, because 3 is a factor of neither 2 nor 10.

Division and multiplication by 32 can be exact, given enough significand width, in both decimal and binary because two, the only prime factor of 32, is a factor of both 10 and 2.

Upvotes: 0

narendra-choudhary
narendra-choudhary

Reputation: 4818

Floating points are stored as binary fractions. Some number cannot be precisely written in base 2 form. So, their approximated value is store.
Now if this approximation had an error of +0.0001 for some number, and if this number is multiplied by 10000, then we our result will shift by value of 0.0001*10000 = 1.

It is same in pretty much all programming languages.

For operations where precision is very important, decimal module should be preferred.

i also try decimal module but its not work for me or maybe i dont know how to use decimal module to get exact answer

Your example, using decimal module, will look something like:

import decimal

value = decimal.Decimal(454546456756765675454)
vd = value/decimal.Decimal(32)
vm = vd*32

diff = vm - value
assert diff == decimal.Decimal(0)
# assert diff == 0.0

Upvotes: 1

Related Questions