Jake B.
Jake B.

Reputation: 465

Numpy array element-by-element comparison optimization

Let a be a numpy array of length n. Does the statement a == max(a) calculate the expression max(a) n-times or just one?

Upvotes: 0

Views: 80

Answers (2)

bogatron
bogatron

Reputation: 19169

It only evaluates max once. You could test this yourself by writing your own function:

def mymax(x):
    print("Calling mymax.")
    return max(x)

Then try

a == mymax(a)

Upvotes: 1

shx2
shx2

Reputation: 64318

It computes max(a) once, then it compares the (scalar) result against each (scalar) element in a, and creates a bool-array for the result.

Upvotes: 1

Related Questions