Search code examples
pythonarraysvectorizationinterpolationnumba

Building an array from an interpolating function faster in Python


I have an interpolating function f(x) that I have created using interp1d.

Now from the function f(x), I have to construct a function f(y,z) where x=(y-z)/2.

I am doing it using a nested loop like so:

f = lambda x: x**3
y = np.arange(0,100)
z = np.arange(0,100)
fnew = np.zeros((100,100))
for i in range(0,100):
    for j in range(0,100):
        fnew[i,j] = f((y[j]-z[i])/2)

For illustration, I have taken the function f=x^3. However, since I am iterating over ~ 8000 values for both i and j, and since f(x) is an interpolating function, the loop is taking very long (obviously) and numba fails to work.

Is there a better way to achieve this?


Solution

  • I would exploit broadcasting rules:

    f = lambda x: x ** 3
    y = np.arange(100)
    z = np.arange(100)
    fnew = f((y[np.newaxis, :] - z[:, np.newaxis]) * 0.5)