Numpy 简明教程
NumPy - Array From Numerical Ranges
在本章节中,我们将会介绍如何从数值范围创建数组。
In this chapter, we will see how to create an array from numerical ranges.
numpy.arange
此函数返回一个 ndarray 对象,其中包含给定范围内间隔均匀的值。该函数的格式如下所示 −
This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows −
numpy.arange(start, stop, step, dtype)
构造函数需要以下参数。
The constructor takes the following parameters.
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 |
以下示例显示了如何使用此函数。
The following examples show how you can use this function.
Example 1
import numpy as np
x = np.arange(5)
print x
其输出如下所示 −
Its output would be as follows −
[0 1 2 3 4]
numpy.linspace
此函数类似于 arange() 函数。在此函数中,而不是步长,指定了区间内间隔均匀的值的数量。此函数的使用方式如下:
This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. The usage of this function is as follows −
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
构造函数需要以下参数。
The constructor takes the following parameters.
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 函数的使用。
The following examples demonstrate the use linspace function.
Example 1
import numpy as np
x = np.linspace(10,20,5)
print x
其输出将为 −
Its output would be −
[10. 12.5 15. 17.5 20.]
numpy.logspace
此函数返回包含以对数刻度固定间隔排列的数字的 ndarray 对象。刻度的起始和结束端点是基数的指数,通常为 10。
This function returns an ndarray object that contains the numbers that are evenly spaced on a log scale. Start and stop endpoints of the scale are indices of the base, usually 10.
numpy.logspace(start, stop, num, endpoint, base, dtype)
下列参数决定 logspace 函数的输出。
Following parameters determine the output of logspace function.
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 |
以下示例将帮助您理解 logspace 函数。
The following examples will help you understand the logspace function.