Issue
I have been switching from Matlab to IPython. In IPython, if we multiply 3.1 by 2.1, the following is the result:
In [297]:
3.1 * 2.1
Out[297]:
6.510000000000001
There is a small round-off error. It is not a big problem, but it is a little bit annoying. I assume that it appeared while converting decimal numbers into binary numbers and vice versa, is it right?
However, in Numpy array, the result is correct:
>>> np.array([3.1 * 2.1])
array([ 6.51])
In Matlab command line prompt, also the result is correct:
>> 3.1 * 2.1
ans =
6.5100
The above round-off error in Python looks annoying. Are there some ways to avoid this error in the python interactive mode or in IPython?
Solution
The numpy result is no more precise than the pure Python one - the floating point imprecision is just hidden from you because, by default, numpy prints fewer decimal places of the result:
In [1]: float(np.array([3.1 * 2.1]))
Out[1]: 6.510000000000001
You can control how numpy displays floating point numbers using np.set_printoptions
. For example, to print 16 decimal places rather than the usual 8:
In [2]: np.set_printoptions(precision=16)
In [3]: np.array([3.1 * 2.1])
Out[3]: array([ 6.5100000000000007])
In IPython you can also use the %precision
magic to control the number of decimal places that are displayed when pretty-printing normal Python floats:
In [4]: %precision 8
Out[4]: u'%.8f'
In [5]: 3.1 * 2.1
Out[5]: 6.51000000
Note that this is purely cosmetic - the value of 3.1 * 2.1
will still be equal to 6.5100000000000006750155990...
rather than 6.51
.
Answered By - ali_m
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.