這一章中,我們會學到如何從數(shù)值范圍創(chuàng)建數(shù)組。
numpy.arange這個函數(shù)返回ndarray對象,包含給定范圍內(nèi)的等間隔值。
numpy.arange(start, stop, step, dtype)
構造器接受下列參數(shù):
| 序號 | 參數(shù)及描述 |
|---|---|
| 1. | start 范圍的起始值,默認為0 |
| 2. | stop 范圍的終止值(不包含) |
| 3. | step 兩個值的間隔,默認為1 |
| 4. | dtype 返回ndarray的數(shù)據(jù)類型,如果沒有提供,則會使用輸入數(shù)據(jù)的類型。 |
下面的例子展示了如何使用該函數(shù):
import numpy as np
x = np.arange(5)
print x
輸出如下:
[0 1 2 3 4]
import numpy as np
# 設置了 dtype
x = np.arange(5, dtype = float)
print x
輸出如下:
[0. 1. 2. 3. 4.]
# 設置了起始值和終止值參數(shù)
import numpy as np
x = np.arange(10,20,2)
print x
輸出如下:
[10 12 14 16 18]
numpy.linspace此函數(shù)類似于arange()函數(shù)。 在此函數(shù)中,指定了范圍之間的均勻間隔數(shù)量,而不是步長。 此函數(shù)的用法如下。
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
構造器接受下列參數(shù):
| 序號 | 參數(shù)及描述 |
|---|---|
| 1. | start 序列的起始值 |
| 2. | stop 序列的終止值,如果endpoint為true,該值包含于序列中 |
| 3. | num 要生成的等間隔樣例數(shù)量,默認為50 |
| 4. | endpoint 序列中是否包含stop值,默認為ture |
| 5. | retstep 如果為true,返回樣例,以及連續(xù)數(shù)字之間的步長 |
| 6. | dtype 輸出ndarray的數(shù)據(jù)類型 |
下面的例子展示了linspace函數(shù)的用法。
import numpy as np
x = np.linspace(10,20,5)
print x
輸出如下:
[10. 12.5 15. 17.5 20.]
# 將 endpoint 設為 false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print x
輸出如下:
[10. 12. 14. 16. 18.]
# 輸出 retstep 值
import numpy as np
x = np.linspace(1,2,5, retstep = True)
print x
# 這里的 retstep 為 0.25
輸出如下:
(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
numpy.logspace此函數(shù)返回一個ndarray對象,其中包含在對數(shù)刻度上均勻分布的數(shù)字。 刻度的開始和結(jié)束端點是某個底數(shù)的冪,通常為 10。
numpy.logscale(start, stop, num, endpoint, base, dtype)
logspace函數(shù)的輸出由以下參數(shù)決定:
| 序號 | 參數(shù)及描述 |
|---|---|
| 1. | start 起始值是base ** start |
| 2. | stop 終止值是base ** stop |
| 3. | num 范圍內(nèi)的數(shù)值數(shù)量,默認為50 |
| 4. | endpoint 如果為true,終止值包含在輸出數(shù)組當中 |
| 5. | base 對數(shù)空間的底數(shù),默認為10 |
| 6. | dtype 輸出數(shù)組的數(shù)據(jù)類型,如果沒有提供,則取決于其它參數(shù) |
下面的例子展示了logspace函數(shù)的用法。
import numpy as np
# 默認底數(shù)是 10
a = np.logspace(1.0, 2.0, num = 10)
print a
輸出如下:
[ 10. 12.91549665 16.68100537 21.5443469 27.82559402
35.93813664 46.41588834 59.94842503 77.42636827 100. ]
# 將對數(shù)空間的底數(shù)設置為 2
import numpy as np
a = np.logspace(1,10,num = 10, base = 2)
print a
輸出如下:
[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]