Python rounding error with float numbers
Any number that can't be built from exact powers of two can't be represented exactly as a floating point number; it needs to be approximated. Sometimes the closest approximation will be less than the actual number.
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic.
How to fix Python rounding error in Floating Point numbers without using decimal, fractions or any other external libraries?
How to fix Python rounding error in Floating Point numbers without using decimal, fractions or any other external libraries?
Floating Point Arithmetic: Issues and Limitations
(...)there are many different decimal numbers that share the same
nearest approximate binary fraction. For example, the numbers0.1
and0.10000000000000001
and0.1000000000000000055511151231257827021181583404541015625
are all
approximated by3602879701896397 / 2 ** 55
. Since all of these
decimal values share the same approximation, any one of them could be
displayed while still preserving the invarianteval(repr(x)) == x
.(...)this is in the very nature of binary floating-point: this is
not a bug in Python, and it is not a bug in your code either. You’ll
see the same kind of thing in all languages that support your
hardware’s floating-point arithmetic (although some languages may not
display the difference by default, or in all output modes).
emphasis added by me, so I suppose only way to repair float
in this case is to not use float
at all. Which is generally not feasible without decimal, fractions or any other external libraries.
Python round off error
Aside from @Ashwini Chaudhary answer,
Question :
Why is python adding up the trailing 00000000002 when mathematically it is not supposed to be there
Answer :
Because value in the machine is not exact. It's not a bug in Python or the bug in your code either. You will see this exact same problem in all languages that support binary floating-point arithmetic. However, different languages may display it differently (round-off).
Try this:
0.1 + 0.2
You will get
0.30000000000000004
This is because 0.1
can't be represent in Binary form exactly. In base 2, or Binary, 0.1
is the infinity repeating numbers
0.0001100110011001100110011001100110011001100110011...
So, Python decided to round this off instead.
I suggest you read more here.
Python Float rounding errors
floats are inherently imprecise in pretty much every language
if you need exact precision use the Decimal class
from decimal import Decimal
print Decimal("0.3")
if you just need them to look pretty just use format strings when displaying
eg :
"%0.2f"%2.030000000000034
if you want to compare them use some threshold
if num1 - num2 < 1e-3 : print "Equal Enough For Me!"
**see abarnert's comments on thresholding ... this is a very simplified example for a more indepth explanation of epsilon thresholding one article I found is here http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm
Additional Reading:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html (for a detailed explanation)
http://floating-point-gui.de/basic/ (basic tutorial for working with floats in general)
python incorrect rounding with floating point numbers
Python 3 rounds according to the IEEE 754 standard, using a round-to-even approach.
If you want to round in a different way then simply implement it by hand:
import math
def my_round(n, ndigits):
part = n * 10 ** ndigits
delta = part - int(part)
# always round "away from 0"
if delta >= 0.5 or -0.5 < delta <= 0:
part = math.ceil(part)
else:
part = math.floor(part)
return part / (10 ** ndigits) if ndigits >= 0 else part * 10 ** abs(ndigits)
Example usage:
In [12]: my_round(0.3125, 3)
Out[12]: 0.313
Note: in python2 rounding is always away from zero, while in python3 it rounds to even. (see, for example, the difference in the documentation for the round
function between 2.7 and 3.3).
Rounding Problem with Python
If you need exact arithmetic, you could use the decimal module:
import decimal
D=decimal.Decimal
x=D('32.50')*D('0.19')
print(x)
# 6.1750
print(x.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 6.18
y=D('32.50')*D('0.19')*D('3')
print(y)
# 18.5250
print(y.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 18.53
How to fix the floating point error in python
you can try any of the follow methods which is conventional for you
#for two decimal places use 2f, for 3 use 3f
val = 0.1 + 0.2
print(f"val = {val:.2f}")
#output | val = 0.30
#or else
print(round(val,2))
#output | val = 0.30
Related Topics
How to Convert an Rgb Image into Grayscale in Python
How to Input a Regex in String.Replace
How to Split a Text into Sentences
Changing One List Unexpectedly Changes Another, Too
Using Both Python 2.X and Python 3.X in Ipython Notebook
How to Parallelize a Simple Python Loop
Scatter Plot With Different Text At Each Data Point
How to Retrieve a Module'S Path
How to Send an Email With Gmail as Provider Using Python
How to Read CSV Data into a Record Array in Numpy
Installing Specific Package Version With Pip
Remove Empty Strings from a List of Strings
How to Have One Colorbar For All Subplots
How to Expand the Output Display to See More Columns of a Pandas Dataframe