[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] fast sqrt? and profiling



I'd forgotten about that little feature. It's the same with integers as well. Kind of defeats the purpose of allowing builtin types to be subclassed.

Lenard.

Casey Duncan wrote:

The main problem with that approach is this:

>>> v1 = vector2(1,2)
>>> v2 = vector2(3,4)
>>> v3 = v1+v2
>>> type(v1)
<class 'vector.vector2'>
>>> type(v3)
<type 'complex'>

So with simple arithmetic between vectors you get back an unadorned complex object. And if you override __add__, __sub__, etc, you're no better off then with euclid.

You could probably argue that this is a bug in the implementation of complex, but I think the pattern is pretty common that arithmetic using subclasses of built-in types returns objects of the base class instead of the subclass.

-Casey


On Jan 23, 2009, at 10:44 AM, Lenard Lindstrom wrote:

>>> class vector2(complex):
...     def __getitem__(self, index):
...         if index == 0:
...             return self.real
...         elif index == 1:
...             return self.imag
...         else:
...             raise IndexError("index out of range 0..1")
...    ...     def __iter__(self):
...         return iter((self.real, self.imag))
...
>>> v = vector2(1.0, 3.0)
>>> v[0]
1.0
>>> v[1]
3.0
>>> v[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __getitem__
IndexError: index out of range 0..1
>>> (x, y) = v
>>> x
1.0
>>> y
3.0


Casey Duncan wrote:

Yes, complex numbers are built in and implemented in C, whereas Euclid is not and implemented in python. The downside to using complex is that they cannot be indexed or unpacked for passing into apis that expect sequences for vectors (hence the to_tuple() function).

-Casey

On Jan 22, 2009, at 11:36 PM, Emile Kroeger wrote:

Oh, I guess they are pretty much equivalent, even though Casey seems
to say complex have better performance than euclid.

I just use complex because it's available out of the box with Python
:) (and because I didn't know about Euclid; maybe I'll use it if I do
3D)



--
Lenard Lindstrom
<len-l@xxxxxxxxx>