当前位置: 首页> 汽车> 报价 > Numpy库学习之np.linspace函数

Numpy库学习之np.linspace函数

时间:2025/7/9 11:11:24来源:https://blog.csdn.net/qq_46396470/article/details/140426131 浏览次数: 0次

Numpy库学习之np.linspace函数

一、简介

np.linspace 是 NumPy 库中的一个函数,用于在指定的区间内生成【等间距】的数字序列。这个函数非常有用,尤其是在需要在固定间隔内对数据进行采样时。

二、语法和参数

np.linspace 的基本语法如下:

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
  • start:序列的起始值。
  • stop:序列的结束值。
  • num:要生成的样本数量,默认为50。
  • endpoint:布尔值,如果为True,则包含stop值在序列中;如果为False,则不包含。
  • retstep:布尔值,如果为True,则返回样本和步长。
  • dtype:输出数组的类型。如果未指定,则根据其他输入参数推断数据类型。
  • axis:返回的样本数组中沿哪个轴存放样本,0表示沿第一个轴。
三、实例
3.1 基础使用
import numpy as np# 生成从0到10的5个等间距的样本
samples = np.linspace(0, 10, num=5)
print(samples)

输出:

[ 0.   2.5  5.   7.5 10. ]
3.2 包含结束点
# 生成从0到10的11个等间距的样本,包含结束点
samples_with_endpoint = np.linspace(0, 10, num=11, endpoint=True)
print(samples_with_endpoint)

输出:

[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]
3.3 不包含结束点
# 生成从0到10的10个等间距的样本,不包含结束点
samples_without_endpoint = np.linspace(0, 10, num=10, endpoint=False)
print(samples_without_endpoint)

输出:

[0.  0.5 1.  1.5 2.  2.5 3.  3.5 4.  4.5]
3.4 返回步长
# 生成样本并返回步长
samples_with_step = np.linspace(0, 10, num=5, retstep=True)
print("Samples:", samples_with_step[0])
print("Step:", samples_with_step[1])

输出:

Samples: [ 0.   2.5  5.   7.5 10. ]
Step: 2.5
四、注意事项
  • endpoint=False时,num参数表示不包括结束点stop的样本数量,因此实际生成的样本数量会比num多一个。
  • 如果需要更高精度的等间距样本,可以通过设置dtype参数来指定输出数组的数据类型,例如np.float64
关键字:Numpy库学习之np.linspace函数

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: