创建规则排列的数字序列 [英] Creating a sequence of regularly spaced numbers

查看:60
本文介绍了创建规则排列的数字序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个规则排列的数字序列,可以用以下简单代码天真地定义它们:

I create a sequence of regularly spaced numbers that naively could be taken defined with this simple code:

l=6          # Number of elements
h=1          # Spatial regular interval
v=[-h/2]     # First element
for i in range(l,start=1):
    v.append(v[-1]+h)

我正在为此使用np.arange,例如:

I'm using np.arange for that, as in:

np.arange(-h/2, h*(l-.5), h)

但是文档说应该使用np.linspace代替,因为我没有使用整数.

but documentation says that np.linspace should be used instead because I'm not using intergers.

np.linspace(-h/2, h*(l-.5), l, endpoint=False)

这种方法是否能证明失败?

Is this approach fail proof?

推荐答案

np.arange的工作方式是将step添加到start并比较结果是否为>= stop,在这种情况下,它将不会生成最后一个值(端点),否则请重复操作.

np.arange works by adding step to start and comparing if the result is >= stop in which case it will not generate this last value (endpoint), otherwise repeat the operation.

问题在于,由于浮点数在内存中的表示方式,永远无法将它们进行相等比较.以这个例子为例:

The problem is that floating point numbers can never be compared equal, because of the way they are represented in memory. Take this example for instance:

>>> 0.5 + 0.1 + 0.1 + 0.1 < 0.8
True

浮点数的行为可能导致将step=0.1添加到0.7的先前生成的np.arange值中,并且小于stop=0.8.这就是为什么arange有时会返回端点的原因.它并不是真正的返回端点,而是返回一个接近端点的数字,如0.7999999999999999,该数字通过返回浮点数的字符串表示的方法进行了四舍五入.

That behaviour of floating point numbers could cause a step=0.1 to be added to the previous generated value of np.arange of 0.7 and be less than the stop=0.8. This is why sometimes arange seems to return endpoint. It's not really returning endpoint, it's returning a number close to endpoint like 0.7999999999999999 which gets rounded up by the method thats returning the string representation of the floating point number.

在具有固定步数的情况下,对于np.linspace来说不是这种情况,因为您将不会比较浮点数,而是计算设置的步数的值.因此,回答您的问题,是的,按照您的方式使用np.linspace是安全的.检查此 github 线程以获取更多信息.

This is not the case with np.linspace when you have a fixed number of steps, because you wont be comparing floating point numbers but rather calculating the value of a set number of steps. So answering your question, yes it is safe to use np.linspace the way you've done. Check this github thread for more information.

还要注意,我说过您应该有固定数量的步骤.如果您尝试基于startstop计算步骤数,则会遇到类似的问题,就像在其他

Note also that I've said you should have a fixed number of steps. If you are trying to calculate the number of steps based on start and stop you would run into similar problems as you can see on this other answer.

这篇关于创建规则排列的数字序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆