Question

I am working with python and playing with multiplications and divisions but I can't get the accuracy that I want with this operations. The following example may help to reach my point.

Let a = 3 and b = 4, their euclidean norm (sqrt(a*a + b*b)) is 5.0, and divisions work fine, like 3/5.0 which is 0.6, and 4/5.0 = 0.8. But when I want to make the following 3 * -0.8 + 0.6*4 the answer is a little number but not the expected zero.

I know the problems inherent to data type, registers and in general the machine limits, but I think there must be a way that for at least simple computations (like the example) are made with no errors.

Was it helpful?

Solution

You can use Fraction to get an accurate answer:

>>> from fractions import Fraction
>>> Fraction(-8, 10) * 3 + Fraction(6, 10) * 4
Fraction(0, 1)

Or use Decimal:

>>> from decimal import Decimal
>>> Decimal('-0.8') * 3 + Decimal('0.6') * 4
Decimal('0.0')

Beware of the String used in the decimals: using normal numbers will make the decimals use the inaccurate value of the number.

OTHER TIPS

This should give some insight to Python specifically: http://docs.python.org/2/tutorial/floatingpoint.html

However the situation is the same in floating point calculations performed by your processor. Because of how floating point numbers are stored it is impossible to represent the entire continuum of all numbers exactly. When you perform the operation some of the extra "approximation" data at the end of the numbers, which you usually don't see in the output (it gets clipped out), creeps into your calculation. Note that 3.*-8./10.+0.6*4 gives a closer approximation to what you expect, likely because the approximations of 3.*8 and of 10 are closer to the real values than that of 0.8, so you end up with less accumulated error.

Python has a decimal library you can use which uses a different underlying representation, but unless you're only doing a few operations it's going to be slower. If it's more important to get "exact" numbers, then use one of those libraries, otherwise the floating point approximations is usually sufficient. You can find more information here: http://docs.python.org/2/tutorial/floatingpoint.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top