python - Difference of precision/display between numpy.tolist() and list() -
this kind of follow coldspeed's question.
(and not duplicate of is floating point math broken ? btw)
i'm converting list of lists numpy array, , trying convert python list of lists.
import numpy np x = [[ 1.00000000e+00, 6.61560000e-13], [ 2.00000000e+00, 3.05350000e-13], [ 3.00000000e+00, 6.22240000e-13], [ 4.00000000e+00, 3.08850000e-13], [ 5.00000000e+00, 1.11170000e-10], [ 6.00000000e+00, 3.82440000e-11], [ 7.00000000e+00, 5.39160000e-11], [ 8.00000000e+00, 1.75910000e-11], [ 9.00000000e+00, 2.27330000e-10]] x=np.array(x,np.float) print([y.tolist() y in x]) print([list(y) y in x])
result:
[[1.0, 6.6156e-13], [2.0, 3.0535e-13], [3.0, 6.2224e-13], [4.0, 3.0885e-13], [5.0, 1.1117e-10], [6.0, 3.8244e-11], [7.0, 5.3916e-11], [8.0, 1.7591e-11], [9.0, 2.2733e-10]] [[1.0, 6.6155999999999996e-13], [2.0, 3.0535000000000001e-13], [3.0, 6.2223999999999998e-13], [4.0, 3.0884999999999999e-13], [5.0, 1.1117e-10], [6.0, 3.8243999999999997e-11], [7.0, 5.3915999999999998e-11], [8.0, 1.7591e-11], [9.0, 2.2733e-10]]
note trying match python native types fails (same behavior):
x=np.array(x,dtype=float)
so converting lists normal python lists using numpy.tolist
preserves values, whereas forcing iteration calling list
on them introduces rounding errors.
fun fact:
str([y.tolist() y in x])==str([list(y) y in x])
yieldsfalse
(as expected, different printouts)[y.tolist() y in x]==[list(y) y in x]
yieldstrue
(what hell??)
any thoughts? (using python 3.4 64 bits windows)
the reason 2 methods produce different types have different string representations when holding same value. calling np.tolist
converts elements of array float
data type while calling list
not changing data type resulting in numpy.float64
s:
import numpy np x = [[ 1.00000000e+00, 6.61560000e-13], [ 2.00000000e+00, 3.05350000e-13], [ 3.00000000e+00, 6.22240000e-13], [ 4.00000000e+00, 3.08850000e-13], [ 5.00000000e+00, 1.11170000e-10], [ 6.00000000e+00, 3.82440000e-11], [ 7.00000000e+00, 5.39160000e-11], [ 8.00000000e+00, 1.75910000e-11], [ 9.00000000e+00, 2.27330000e-10]] x=np.array(x,np.float) print(type(x[0].tolist()[0])) # `float` print(type(list(x[0])[0])) # `numpy.float64`
as have different string representations (float
getting rounded, while numpy.float64
printing full precision), different results printed , comparison of str([y.tolist() y in x])==str([list(y) y in x])
fails, while value wise comparison passes.
Comments
Post a Comment