python - 为什么 np.linspace(1,5,5, dtype = int, endpoint=False) 会导致包含 1 两次的数组?

标签 python numpy

在寻找复制时:

In [61]: np.arange(0,5)
Out[61]: array([0, 1, 2, 3, 4])

使用 np.linspace(),我观察到:

In [70]: np.linspace(1,5,5, dtype = int, endpoint=False)
Out[70]: array([1, 1, 2, 3, 4])

为什么 np.linspace() 在这种情况下两次包含值 1

最佳答案

因为在您的情况下 linspace 是在 float 和返回值上定义的:

np.linspace(1,5,5, endpoint=False)
array([ 1. ,  1.8,  2.6,  3.4,  4.2])

然后使用 int 作为 dtype 只是四舍五入给你两个 1 的结果:

array([ 1 ,  1,  2,  3,  4])

顺便说一句:如果您想创建包含 integerarrays,使用 np.arange 可能更适合:

np.arange(1,5)
array([ 1,  2,  3,  4])

关于python - 为什么 np.linspace(1,5,5, dtype = int, endpoint=False) 会导致包含 1 两次的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36064207/

相关文章:

Python:字符串连接在for循环中的工作方式不同

Python VTK : Coordinates directly to PolyData

python - 从 Python 网页抓取结果中删除特定字符串

Python:if-endif-statement 在哪里结束?

python - Jinja active_page 在包含的文件中不起作用

python - 将 numpy 数组传递给 cython 中的 C 函数

python - 在Python中匹配以特定扩展名结尾的文件名的简洁方法?

python - urllib3 HTTPResponse.read() 返回空字节

python - 避免 python 循环删除容易出错的值

Python:使用基于嵌套列表中唯一值的列创建 Pandas 数据框