简体   繁体   中英

Python numpy.linspace behaves strangely with floats

I have an issue with numpy linspace

import numpy as np

temp = np.linspace(1,2,11)

for t in temp:
    print(t)

This return :

1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7000000000000002
1.8
1.9
2.0

The 1.7 value looks definitely wrong.

It seems related to this issue https://github.com/numpy/numpy/issues/8909

Does anybody ever had such a problem with numpy.linspace ? is it a known issue ?

François

This is nothing to do with numpy , consider:

>>> temp = np.linspace(1,2,11)
>>> temp
array([1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ])
>>> #                                     ^ look, numpy displays it fine
>>> for t in temp:
...     print(t)
... 
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7000000000000002
1.8
1.9
2.0

The "issue" is with how computers represent floats in general. See: https://docs.python.org/3/tutorial/floatingpoint.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM