Search code examples
pythonnumpyscipyinterpolationlogarithm

Interpolate on a logarithmic scale in python


To interpolate my data I currently use this function:

def myinterp(x, y, der = 0, s = 0):
    tck = interpolate.splrep(x, y, s = sigma)
    xnew = np.arange(x[0], x[-1], (x[-1]-x[0])/x.size)
    ynew = interpolate.splev(xnew, tck, der = n)
    return xnew, ynew

xnew is equivalent to x resampled on a regular grid with dx=(x[-1]-x[0])/x.size. How to do the same but with a resample of x on a logarithmic scale ?


Solution

  • You could just take the Logarithm, resample that linearly, and then take the exponent of it:

    xnew = np.exp(np.arange(log(x[0]), log(x[-1]), log(x[-1]/x[0])/x.size))
    

    which could turn out quite expensive because of the repeated call to exp. A more efficient but slightly more cumbersome way would be to employ the fact that at an logarithmic scale there is a constant factor between subsequent elements:

    f = pow(x[-1]/x[0], 1.0/(x.size-1) )
    xnew[0] = x[0]
    for i in range(1,x.size):
        xnew[i] = xnew[i-1] * f
    

    Edit: your question says dx=(x[-1]-x[0])/x.size which looks strange to me, if you want to represent the same range using the same array size you need

    dx=(x[-1]-x[0]) / (x.size-1)
    

    The same applies to my answer.