我是 numpy 的新手,并查看了檔案https://numpy.org/devdocs/reference/generated/numpy.arange.html 但似乎無法獲得錯誤日志或表明它超過了 int 的停止'3'。float 似乎按預期作業,但不是 int。我相信這是由于 python 如何解釋 int 和 float,但 int 不應該自動舍入 0.5 值嗎? 在 Python https://numpy.org/doc/stable/user/basics.types.html中比較浮點數和整數
我的問題是,arange 為什么以及如何將 int 解釋為停止點是 '6' 而不是 '3',如果使用 int,它不應該在 2 處停止嗎?
非常感謝您的啟發。
x = np.arange(-1, 3, 0.5, dtype=int)
y = np.arange(-1, 3, 0.5, dtype=float)
print('x = ', x)
print('y = ', y)
x = [-1 0 1 2 3 4 5 6]
y = [-1. -0.5 0. 0.5 1. 1.5 2. 2.5]
uj5u.com熱心網友回復:
根據您必須閱讀過的檔案,因為您的示例與那里給出的示例接近
Another stability issue is due to the internal implementation of
`numpy.arange`.
The actual step value used to populate the array is
``dtype(start step) - dtype(start)`` and not `step`. Precision loss
can occur here, due to casting or due to using floating points when
`start` is much larger than `step`. This can lead to unexpected
behaviour.
那dtype(start step) - dtype(start):
In [25]: int(-1 .5) - int(-1)
Out[25]: 1
看起來它最初使用與浮點情況相同的數學計算要回傳的值的數量 - 因此x具有y相同的長度。
ceil((stop - start)/step)
In [29]: np.ceil((3-(-1))/.5)
Out[29]: 8.0
我的猜測是,它會[29]隨著[25]步驟“迭代”值。stop在達到/通過' 邏輯之前,它不是“迭代”。
uj5u.com熱心網友回復:
對我的問題的回答是 hpaulj 提到的,正確使用 arange 可能會導致意外行為。int 的小數點是不好的做法,因此導致了這種行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449434.html
上一篇:如何在matplotlib.pyplot中將兩個圖形一起列印,使它們形成一個完整的圖形
下一篇:如何將這個串列垂直重塑為水平
