在 NumPy 中指定区间内返回等间距的数字并设置要生成的样本数


要在指定区间内返回等间距的数字,请在 Python NumPy 中使用 **numpy.linspace()** 方法。第一个参数是“**start**”,即序列的起始位置。第二个参数是“**end**”,即序列的结束位置。第三个参数是 **num**,即要生成的样本数。

除非将 endpoint 设置为 False,否则 stop 是序列的结束值。在这种情况下,序列包含除 num + 1 个等间距样本中的最后一个样本之外的所有样本,因此 stop 将被排除。请注意,当 endpoint 为 False 时,步长会发生变化。

dtype 是输出数组的类型。如果未给出 dtype,则从 start 和 stop 推断数据类型。推断出的 dtype 永远不会是整数;即使参数会生成一个整数数组,也会选择浮点数。结果中存储样本的轴。仅当 start 或 stop 为数组状时才相关。默认情况下 (0),样本将沿着在开头插入的新轴。使用 -1 在末尾获取轴。

步骤

首先,导入所需的库 -

import numpy as np

要在指定区间内返回等间距的数字,请在 Python NumPy 中使用 numpy.linspace() 方法 -

arr = np.linspace(100, 200, num = 10)
print("Array...
", arr)

获取数组类型 -

print("
Type...
", arr.dtype)

获取数组的维度 -

print("
Dimensions...
",arr.ndim)

获取数组的形状 -

print("
Shape...
",arr.shape)

获取元素数量 -

print("
Number of elements...
",arr.size)

示例

import numpy as np

# To return evenly spaced numbers over a specified interval, use the numpy.linspace() method in Python Numpy
# The 1st parameter is the "start" i.e. the start of the sequence
# The 2nd parameter is the "end" i.e. the end of the sequence
# The 3rd parameter is the num i.e the number of samples to generate. Default is 50.
arr = np.linspace(100, 200, num = 10)
print("Array...
", arr) # Get the array type print("
Type...
", arr.dtype) # Get the dimensions of the Array print("
Dimensions...
",arr.ndim) # Get the shape of the Array print("
Shape...
",arr.shape) # Get the number of elements print("
Number of elements...
",arr.size)

输出

Array...
[100. 111.11111111 122.22222222 133.33333333 144.44444444
155.55555556 166.66666667 177.77777778 188.88888889 200. ]

Type...
float64

Dimensions...
1

Shape...
(10,)

Number of elements...
10

更新于: 2022年2月8日

3K+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.