用于浮点开始&的numpy范围停止 [英] numpy arange for floating point start & stop

查看:78
本文介绍了用于浮点开始&的numpy范围停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望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

如果用户输入startendincrement,如果增量的确切值不是关键性的,只需将linspacenum = 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范围停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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