terça-feira, 26 de outubro de 2010

Python class for quaternions


Last August in Dublin (at DCU) I presented a tutorial about Python in Scientific Computing.

While there I thought it was appropriate to give a native example (in Rome be Roman) and so I choose the Quaternions. This is a good excuse as any other to present the multiple features of python for science. :-)

The picture above is carved in the Broom Bridge, over the Royal Canal, and where supposedly Hamilton had the inspiration to come with such beasts :-) . I had described before (in Portuguese) my hazard quest to find the place. An yearly event, at 16th of October, gets people together to visit the place and probably for a couple of drinks. :-)

While preparing the course I searched for python implementations of the quaternions and I have only found code related with graphics transforms (where the quaternions can be useful).
In the same spirit of Free/Open Source Software, to scratch a itch, I make available my implementation of  a python class that implements the quaternions and that deals transparently with the complex numbers.

The code can be found at my homepage.

Here it is a sample:

    a = Quaternion(1, -2)
    b = Quaternion(1, 2, -3, 4)
    c = 1 - 2j

    print "a =", a
    print "b =", b
    print "c =", c

    print a + b
    print a - c

    print a*b
    print a*c

    print 2*a

    print b*b.conjugate()
    print abs(b)**2

And the resulting output:

a = +1-2*i+0*j+0*k
b = +1+2*i-3*j+4*k
c = (1-2j)
+2+0*i-3*j+4*k
+0+0*i+0*j+0*k
+5+0*i+5*j+10*k
-3-4*i+0*j+0*k
+2-4*i+0*j+0*k
+30+0*i+0*j+0*k
30.0

I hope this helps others who have the same problem I had. :-)

2 comentários:

Unknown disse...

[Sorry that this is in english]
There are bugs in __div__ , __rdiv__
in that you multiply by abs(...)**2 rather than divide. Otherwise, a good and useful implementation.

José Matos disse...

[No problem, as you saw some post are in English and others in Portuguese :-) ]

Thanks for the remark, updating this package is (has been) on my plans but meanwhile a little (baby) girl showed up and so my free time is less than I what I would like. :-)