p-value
p-value

Reputation: 648

Behavior of numpy.swapaxes

Can anyone please explain the following behavior of numpy.swapaxes:

import numpy as np
from copy import deepcopy

n = 10 # Works fine, but doesn't if set n = 100
x = rand.uniform(size=(n, n, n))
x0 = deepcopy(x)
x += np.swapaxes(x, 0, 1)  # Works fine if do x = x + np.swapaxes(x, 0, 1) instead...
temp = x0 + np.swapaxes(x0, 0, 1)
print np.linalg.norm(x - temp)

The printed error is zero when n = 10, but not when n = 1000. Why is this so? The code also works fine if we do x = x + np.swapaxes(x, 0, 1) instead of x += np.swapaxes(x, 0, 1). (It has been quite frustrating to debug, since the code works on small samples...)

Upvotes: 1

Views: 963

Answers (1)

B. M.
B. M.

Reputation: 18638

The problem arise because you modify data you are reading ...

You will understand the problem here.

Some extracts:

  • This is a design issue, not really a bug.
  • Numpy's general philosophy is to provide as much safety as possible without compromising on speed.
  • [Correcting that] ... will cause unpredictable slowdowns and increased memory use in situations that are already well defined and work correctly.

Wisdom Rule : NEVER modify data you are reading.

Upvotes: 1

Related Questions