Home > Enterprise >  Building an array from an interpolating function faster in Python
Building an array from an interpolating function faster in Python

Time:11-26

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?

CodePudding user response:

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)

CodePudding user response:

Not sure how it will work with numba, but I think most pythonic way of creating a new function would be this:

g = lambda y, z: f((y-z)/2)

that way you can simply do this inside a loop:

fnew[i,j] = g(i, j)
  • Related