python:生成间距不均匀的数组 [英] python: generate unevenly spaced array

查看:367
本文介绍了python:生成间距不均匀的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个由下限值和上限值限制的数组,该数组具有n个元素,类似于:

I would like to generate an array bounded by a lower and upper value with n elements similar to:

def my_lin(lb, ub, steps):
    dx = (ub-lb) / (steps-1)
    return [lb + i*dx for i in range(steps)]

my_lin(0,10,11)

但我希望更多的值更接近较低的值值。某种谐波间隔。我不想有一个对数间距。

But I would like to have more values closer to the lower value. Some kind of harmonic spacing. I do not want to have a logarithmic spacing.

我想这很简单,但我无法弄清楚。非常感谢您的帮助。

I guess it is rather simple but I cannot figure it out. Any help is highly appreciated.

编辑:

我想出了以下快速解决方案:

I came up with following quick solution:

def harm_series(lb,n):
    return [float(lb)/float(i) for i in range(1,n) ]


推荐答案

查找函数 f ,它在 [0,1] 内具有您想要的间距(请注意 f(0)== 0和f(1)== 1 应该保留),然后应用 f(i * dx /(ub-lb))*(ub-lb)

Find a function f which has your desired spacing within [0,1] (note that f(0)==0 and f(1)==1 should hold) and then apply f(i*dx/(ub-lb))*(ub-lb).

我个人喜欢此功能,但还有更多功能。
例如,尝试以下操作:

I personally like power functions for this but there is many more. For example, try this:

def my_lin(lb, ub, steps, spacing=1.1):
    span = (ub-lb)
    dx = 1.0 / (steps-1)
    return [lb + (i*dx)**spacing*span for i in range(steps)]

lin = my_lin(0, 10, 11)
print lin
# visualize the spacing
print ''.join(' '*int(2*a)+'*' for a in lin)

打印:

[0.0, 0.7943282347242814, 1.702679845041569, 2.6597044516956405, 3.6497741462219233, 4.665164957684037, 5.701201299034059, 6.754727665838724, 7.823462148343428, 8.905673323855929, 10.0]
* *   *     *       *         *           *             *               *                 *                    *

现在使用参数 spacing 可以正常工作像这样:

Now with the parameter spacing it works like this:


  • 离零越近,您在 ub

  • 从1到另一个方向越远,mo它们是否聚集在 lb

  • 如果 spacing 正好为1,则它们是等距

  • The closer you get to zero, the more your values gather around ub
  • The farther you go away from 1 into the other direction, the more they gather around lb
  • If spacing is exactly 1, they are equally spaced

这篇关于python:生成间距不均匀的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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