【问题标题】:python nodal/piecewise-linear power-law generatorpython节点/分段线性幂律发生器
【发布时间】:2015-01-14 13:58:59
【问题描述】:

我需要高效的 p​​ython 代码,它返回(不适合)一个分段线性(或实际上是分段幂律)连续函数,用于由它们的位置定义的任意数量的节点(/极点/控制点)加上(最好) 斜率而不是幅度。例如,对于三件(四个节点),我有:

def powerLawFuncTriple(x,C,alpha,beta,gamma,xmin,xmax,x0,x1):

    """
    Extension of the two-power-law version described at
       http://en.wikipedia.org/wiki/Power_law#Broken_power_law
    """

    if x <= xmin or x > xmax:
        return 0.0
    elif xmin < x <= x0:
        n = C * (x ** alpha)
    elif x0 < x <= x1:
        n = C * x0**(alpha-beta) * (x ** beta)
    elif x1 < x <= xmax:
        n = C  * x0**(alpha-beta) * x1**(beta-gamma) * (x ** gamma)

    return n

是否已经存在任何有用的函数,否则编写代码以生成这些函数的有效方法是什么?也许这相当于评估而不是拟合其中一个 scipy 内置插件。

有些相关:Fitting piecewise function in Python

一个可能的答案可能是:

def piecewise(x,n0,posns=[1.0,2.0,3.0],alpha=[-2.0,-1.5]):

    if x <= posns[0] or x > posns[-1]: return 0.0

    n=n0*x**alpha[0]
    np=len(posns)
    for ip in range(np):
        if posns[ip] < x <= posns[ip+1]: return n
        n *= (posns[ip+1]/float(x))**(alpha[ip]-alpha[ip+1])
    return n

但这必须随着 x 的增加而变慢。列表理解或其他任何东西会加速循环吗?

谢谢!

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    最后我选择了出色的 CosmoloPy 模块:

    http://pydoc.net/Python/CosmoloPy/0.1.103/cosmolopy.utils

    class PiecewisePowerlaw()
    
    """
    You can specify the intervals and power indices, and this class
    will figure out the coefficients needed to make the function
    continuous and normalized to unit integral.
    """
    

    似乎工作得很好。

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 2011-01-07
      • 2023-04-04
      • 1970-01-01
      • 2015-11-23
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多