Create numpy array start from 0 to 1 with increment 0.1

huangapple go评论72阅读模式
英文:

Create numpy array start from 0 to 1 with increment 0.1

问题

"1" 不包括在数组中,要如何包括 "1" 在数组中?是手动将 "1" 添加到数组中,还是有其他方法?

【翻译结果】
"1" is not included in the array. How to include "1" in the array? Do we manually add "1" to the array, or are there any other ways?

英文:

I'm studying in python. I want to create numpy array in python, start from 0 to 1 with increment 0.1. This is the code:

import numpy as np
t=np.arange(0, 1, 0.1)
print(t)

the result is

[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

But "1" is not include in array, how to include 1 in array? Does we manually adding 1 to array, or any other ways?

答案1

得分: 2

numpy.arange文档所述:

> arange(stop): 生成的值在半开区间内,即 [0, stop)(换句话说,该区间包括起始值但不包括结束值)。

> arange(start, stop): 生成的值在半开区间 [start, stop) 内。

> arange(start, stop, step):生成的值在半开区间 [start, stop) 内,值之间的间距由step指定。

因此,要包括1,只需将代码更改为 np.arange(0, 1.1, 0.1)(任何大于1且小于或等于1.1的值都可以)。

>>> np.arange(0, 1.1, 0.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
英文:

As stated in the np.arange documentation

> arange(stop): Values are generated within the half-open interval
> [0, stop) (in other words, the interval including start but
> excluding stop).
>
> arange(start, stop): Values are generated within the half-open interval [start, stop).
>
> arange(start, stop, step) Values are generated within the half-open interval [start, stop), with spacing between values given by
> step.

So, to include 1, just change the code to np.arange(0, 1.1, 0.1) (any value greater than 1 and less or equal with 1.1 would work)

>>> np.arange(0, 1.1, 0.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

答案2

得分: 1

Python有一个约定,即在指定范围时,它将从起始值迭代到结束值之前(例如,for x in range(0, 15)将为x分配从0到14的每个值--而不是15)。在你的情况下,你可以通过将中间参数(对应于迭代器将在其之前停止的结束值)设置为略高于1(例如1.1),或者像你提到的那样手动添加1.到末尾来解决这个问题。

英文:

Python has a convention where, when specifying a range, it will iterate over that range from the start value to just before the end value (e.g. for x in range(0, 15) will assign x every value from 0 to 14--not 15). In your case, you can solve that by either setting the middle parameter (which correlates to the end value the iterator will stop just before) to be just over 1 (e.g. 1.1), or by manually appending 1. to the end like you mentioned.

huangapple
  • 本文由 发表于 2023年6月19日 09:32:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503151.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定