问题描述
我希望numpy创建一个完整的列表,给定参数开始,停止和递增,但是遇到了一些麻烦:
I want numpy to create a full list, given the parameters start, stop and increment, but ran into some troubles:
In[2]: import numpy as np
In[3]: np.arange(2.0, 2.4, 0.2)
Out[3]: array([ 2. , 2.2])
In[4]: np.arange(2.0, 2.6, 0.2)
Out[4]: array([ 2. , 2.2, 2.4, 2.6])
In[5]: np.arange(2.0, 2.8, 0.2)
Out[5]: array([ 2. , 2.2, 2.4, 2.6])
我真正想要的是:
array([ 2. , 2.2, 2.4])
现在,我了解到,如果浮点数据类型降为固定值,则应避免使用该类型.我知道将开始/停止/增量乘以100会更好,但是问题是我无法确定用户将要提供多少个小数.我还有什么方法可以使用Float做到这一点,还是有更好的方法来解决这个问题?
Now, I've learned that I should avoid the floating point data type if it comes down to fixed values. I know it would be better to multiply start/stop/increment by 100, but the problem is that I cannot tell, how many decimals the user is going to supply. Is there any way I can still do that with Float or is there a better way to solve this?
现在,它可以与将0.0000001添加到最终值的明显解决方案一起使用.但这在我的代码中看起来很可怕...我希望能以某种方式很好地解决此问题
It works now with the obvious solution of adding 0.0000001 to the end-value. But this looks horrible in my code...I'd hope to fix this nicely somehow
推荐答案
您可以指定用户应该输入哪些值吗?对于这种类型的生成,我认为 linspace
可能更好,因为它包含了end
参数
Could you specify which values the user is supposed to enter? For that kind of generation, I think linspace
could be better as it includes the end
parameter
如果用户输入start
,end
和increment
,如果增量的确切值不是关键性的,只需将linspace
与num = int((end-start)/increment+1)
一起使用.
if the user enters start
, end
, and increment
, just use linspace
with num = int((end-start)/increment+1)
if the exact value of the increment is not critical.
将1e-4
调整为您认为可以接受的相对误差(甚至可以将其添加为用户定义的变量).
adapt 1e-4
to the relative error you deem acceptable (you can even add it as a user-defined variable).
eps = 1e-4*(stop-start)
num = int((stop-start)/(incr-eps)+1)
np.linspace(start, stop,num)
这篇关于用于浮点开始&的numpy范围停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!