Lin
Lin

Reputation: 1203

double loop optimizations

I want to calculate some linear interpolants and I'm using the following python code:

# Points array
V=np.array([-1/2, 1/2, 3/2, 5/2, 7/2, 9/2])

# Lagrange Interpolant
D=np.ones_like(V);

# Calculation
for n,i in enumerate(V):
    for m,j in enumerate(V):
        # This should exist otherwise we divide by zero
        if m!=n:
            D[n] *= (i-j)

# Invert Array
D=1/D

It works fine. But since I will run this billion of times, I would like to know if there is faster approaches.

Upvotes: 2

Views: 74

Answers (1)

Divakar
Divakar

Reputation: 221564

Leverage broadcasting to replace the two nested loops -

mult = V[:,None] - V
np.fill_diagonal(mult,1)
out = mult.prod(1)

Upvotes: 4

Related Questions