[Numpy-discussion] Faster way to generate a rotation matrix?

David Warde-Farley dwf@cs.toronto....
Wed Mar 4 00:56:23 CST 2009


On 3-Mar-09, at 11:41 PM, Jonathan Taylor wrote:

> def rotation(theta, R = np.zeros((3,3))):

Hey Jon,

Just a note, in case you haven't heard this schpiel before: be careful  
when you use mutables as default arguments. It can lead to unexpected  
behaviour down the line.

The reason is that the np.zeros() is only called once when the  
function is read by the interpreter, and that reference is retained  
between calls.Example:

 >>> def f(a=[0,0,0]):
...     print sum(a)
...     a[0] += 1
...
 >>> f()
0
 >>> f()
1
 >>> f()
2


In your example this is fine, since you're overwriting every single  
value in the function body, but if you weren't, it would lead to  
problems that would be difficult to debug.

(On a related note never try and reverse an array in-place with slice  
syntax. i.e. a[:] = a[::-1] is bad mojo and cost me about a day. :P)

Cheers,

David


More information about the Numpy-discussion mailing list