gpt4 book ai didi

python - 哪种 dtype 是正确的,可以防止 numpy.arange() 获得错误的长度?

转载 作者:行者123 更新时间:2023-12-01 07:42:27 25 4
gpt4 key购买 nike

我正在尝试获取一个包含 200 个值且范围内相差 40 个值的移位数组。

因此我使用 numpy.arange(a, b, 0.2) 起始值 a=0> 和 b=40 并向上 (a=0.2 b=40.2, a=0.4 b=40.4 等等)。

当我到达 numpy.arange(25.4, 65.4, 0.2) 时,我突然得到一个长度为 201 值的数组:

x = numpy.arange(25.2, 65.2, 0.2)
print(len(x))

返回200

x = numpy.arange(25.4, 65.4, 0.2)
print(len(x))

返回201

到目前为止,我注意到这种情况的发生可能是由于数据类型的舍入问题......

我知道 numpy.arrange() 中有一个选项“dtype”:

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

问题是哪种数据类型适合这个问题,为什么? (我对jet数据类型不太有信心,https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html#numpy.dtype并没有帮助我解决这个问题。请帮忙!

最佳答案

当您想要精确控制相邻元素之间的差异时,

np.arange 最有用。另一方面,np.linspace 可以让您精确控制元素总数。听起来您想使用 np.linspace 代替:

import numpy as np

offset = 25.4

x = np.linspace(offset, offset + 40, 200)

print(x)
print(len(x))

这是np.linspace的文档页面:https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html

关于python - 哪种 dtype 是正确的,可以防止 numpy.arange() 获得错误的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56633250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com