問題描述
有沒有辦法在 0 和 1 之間步進 0.1?
Is there a way to step between 0 and 1 by 0.1?
我以為我可以這樣做,但它失敗了:
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
相反,它說 step 參數不能為零,這是我沒想到的.
Instead, it says that the step argument cannot be zero, which I did not expect.
推薦答案
比起直接使用小數步長,用你想要的點數來表達要安全得多.否則,浮點舍入錯誤很可能會給你一個錯誤的結果.
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
您可以使用 linspace 函數NumPy 庫(它不是標準庫的一部分,但相對容易獲得).linspace
需要返回多個點,還可以讓您指定是否包含正確的端點:
You can use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace
takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
如果你真的想使用浮點步進值,你可以使用 numpy.arange
.
If you really want to use a floating-point step value, you can, with numpy.arange
.
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
浮點舍入誤差會導致問題.這是一個簡單的例子,其中舍入錯誤導致 arange
在它應該只產生 3 個數字時產生一個長度為 4 的數組:
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange
to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
這篇關于如何使用小數范圍()步長值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!