Numpy库学习之np.linspace函数

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值