B05_NumPy从数值范围创建数组(numpy.arange,numpy.linspace,numpy.logspace)
NumPy 從數(shù)值范圍創(chuàng)建數(shù)組
numpy.arange
numpy 包中的使用 arange 函數(shù)創(chuàng)建數(shù)值范圍并返回 ndarray 對象,函數(shù)格式如下:
numpy.arange(start, stop, step, dtype)根據(jù) start 與 stop 指定的范圍以及 step 設(shè)定的步長,生成一個 ndarray。
參數(shù)說明:
| start | 起始值,默認(rèn)為0 |
| stop | 終止值(不包含) |
| step | 步長,默認(rèn)為1 |
| dtype | 返回ndarray的數(shù)據(jù)類型,如果沒有提供,則會使用輸入數(shù)據(jù)的類型。 |
實例
生成0到5的數(shù)組
輸出結(jié)果如下:
[0 1 2 3 4]設(shè)置返回類型位 float:
# -*- coding: UTF-8 -*-import numpy as npx = np.arange(5, dtype = float) print(x)輸出結(jié)果如下:
[0. 1. 2. 3. 4.]設(shè)置了起始值、終止值及步長:
# -*- coding: UTF-8 -*-import numpy as npx = np.arange(10,20,2) print(x)輸出結(jié)果如下:
[10 12 14 16 18]numpy.linspace
numpy.linspace 函數(shù)用于創(chuàng)建一個一維數(shù)組,數(shù)組是一個等差數(shù)列構(gòu)成的,格式如下:
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)參數(shù)說明:
| start | 序列的起始值 |
| stop | 序列的終止值,如果endpoint為true,該值包含于數(shù)列中 |
| num | 要生成的等步長的樣本數(shù)量,默認(rèn)為50 |
| endpoint | 該值為 true 時,數(shù)列中中包含stop值,反之不包含,默認(rèn)是True。 |
| retstep | 如果為 True 時,生成的數(shù)組中會顯示間距,反之不顯示。 |
| dtype | ndarray 的數(shù)據(jù)類型 |
以下實例用到三個參數(shù),設(shè)置起始點為 1 ,終止點為 100,數(shù)列個數(shù)為 10。
import numpy as np a = np.linspace(1,100,10) print(a)輸出結(jié)果為:
[ 1. 12. 23. 34. 45. 56. 67. 78. 89. 100.]設(shè)置元素全部為100的等差數(shù)列
import numpy as np a = np.linspace(100,100,10) print(a)輸出結(jié)果為:
[100. 100. 100. 100. 100. 100. 100. 100. 100. 100.]將endpoint設(shè)為false,不包含終止值:
import numpy as np a = np.linspace(10,20,5, endpoint = False) print(a)輸出結(jié)果為:
[10. 12. 14. 16. 18.]如果將endpoint設(shè)為true,則會包含20.
以下實例設(shè)置間距。
輸出結(jié)果為:
(array([ 1., 12., 23., 34., 45., 56., 67., 78., 89., 100.]), 11.0) [[ 1.][ 12.][ 23.][ 34.][ 45.][ 56.][ 67.][ 78.][ 89.][100.]]numpy.logspace
numpy.logspace 函數(shù)用于創(chuàng)建一個于等比數(shù)列。格式如下:
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)base參數(shù)意思是取對數(shù)的時候log的下標(biāo)。
| start | 序列的起始值為:base ** start |
| stop | 序列的終止值為:base ** stop。如果endpoint為true,該值包含于數(shù)列中 |
| num | 要生成的等步長的樣本數(shù)量,默認(rèn)為50 |
| endpoint | 該值為 true 時,數(shù)列中中包含stop值,反之不包含,默認(rèn)是True。 |
| base | 對數(shù) log 的底數(shù)。 |
| dtype | ndarray 的數(shù)據(jù)類型 |
實例:
import numpy as np # 默認(rèn)底數(shù)是10 a = np.logspace(1.0,2.0,num=10) print(a)輸出結(jié)果為:
[ 10. 12.91549665 16.68100537 21.5443469 27.8255940235.93813664 46.41588834 59.94842503 77.42636827 100. ]將對數(shù)的底數(shù)設(shè)置為2:
import numpy as np a = np.logspace(0,9,10,base=2) print(a)輸出如下:
[ 1. 2. 4. 8. 16. 32. 64. 128. 256. 512.]總結(jié)
以上是生活随笔為你收集整理的B05_NumPy从数值范围创建数组(numpy.arange,numpy.linspace,numpy.logspace)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: B04_NumPy从已有的数组创建数组(
- 下一篇: LG是哪国品牌 宣布正式停产手机