📜  NumPy-数值范围内的数组

📅  最后修改于: 2020-11-08 07:35:02             🧑  作者: Mango


在本章中,我们将看到如何从数值范围创建数组。

numpy.arange

此函数返回一个ndarray对象,该对象包含给定范围内的均匀间隔的值。该函数的格式如下-

numpy.arange(start, stop, step, dtype)

构造函数采用以下参数。

Sr.No. Parameter & Description
1

start

The start of an interval. If omitted, defaults to 0

2

stop

The end of an interval (not including this number)

3

step

Spacing between values, default is 1

4

dtype

Data type of resulting ndarray. If not given, data type of input is used

以下示例显示如何使用此函数。

例子1

import numpy as np 
x = np.arange(5) 
print x

其输出如下-

[0  1  2  3  4]

例子2

import numpy as np 
# dtype set 
x = np.arange(5, dtype = float)
print x

在这里,输出将是-

[0.  1.  2.  3.  4.] 

例子3

# start and stop parameters set 
import numpy as np 
x = np.arange(10,20,2) 
print x

其输出如下-

[10  12  14  16  18] 

numpy.linspace

此函数类似于arange()函数。在此函数,将指定间隔之间的均匀间隔数,而不是步长。此函数的用法如下-

numpy.linspace(start, stop, num, endpoint, retstep, dtype)

构造函数采用以下参数。

Sr.No. Parameter & Description
1

start

The starting value of the sequence

2

stop

The end value of the sequence, included in the sequence if endpoint set to true

3

num

The number of evenly spaced samples to be generated. Default is 50

4

endpoint

True by default, hence the stop value is included in the sequence. If false, it is not included

5

retstep

If true, returns samples and step between the consecutive numbers

6

dtype

Data type of output ndarray

以下示例演示了linspace函数的用法。

例子1

import numpy as np 
x = np.linspace(10,20,5) 
print x

它的输出将是-

[10.   12.5   15.   17.5  20.]

例子2

# endpoint set to false 
import numpy as np 
x = np.linspace(10,20, 5, endpoint = False) 
print x

输出将是-

[10.   12.   14.   16.   18.]

例子3

# find retstep value 
import numpy as np 

x = np.linspace(1,2,5, retstep = True) 
print x 
# retstep here is 0.25

现在,输出将是-

(array([ 1.  ,  1.25,  1.5 ,  1.75,  2.  ]), 0.25)

numpy.logspace

此函数返回一个ndarray对象,该对象包含在对数刻度上均匀间隔的数字。标度的起点和终点是基准的索引,通常为10。

numpy.logspace(start, stop, num, endpoint, base, dtype)

以下参数确定logspace函数的输出。

Sr.No. Parameter & Description
1

start

The starting point of the sequence is basestart

2

stop

The final value of sequence is basestop

3

num

The number of values between the range. Default is 50

4

endpoint

If true, stop is the last value in the range

5

base

Base of log space, default is 10

6

dtype

Data type of output array. If not given, it depends upon other input arguments

以下示例将帮助您了解日志空间函数。

例子1

import numpy as np 
# default base is 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.    ]

例子2

# set base of log space to 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.]