Richie Bendall
Richie Bendall

Reputation: 9212

Use case for np.log2 vs math.log2

Sometimes, authors use np.log2 instead of math.log2. For example, in this PyTorch code:

num_pools = int(np.log2(spatial))

(where spatial is a Python number)

Because math.log2 is a built-in an included battery, I don't see a reason for calling np.log2 instead - is it maybe to follow convention, or because np.log2 is thought to be faster?

Upvotes: 0

Views: 368

Answers (1)

jared
jared

Reputation: 9011

If we have numpy arrays, then np.log2 should be used because it works on arrays while math.log2 does not. If we have a scalar, math.log2 is faster and therefore preferred. As for why people use np.log2 for scalars, I can only speculate. It's most likely because they already have it imported and don't care about the minor speed improvement gained by using math.log2.

Upvotes: 1

Related Questions