[Tutor] imaginary number class

Gregor Lingl glingl@aon.at
Tue, 25 Jun 2002 18:17:38 +0200


Dear Rob!
Unfortunately I haven't got much time to answer to
your interesting question at the moment. Nevertheless
a few remarks:

Rob Andrews schrieb:

> For your enjoyment:
>
> I'm staring down the barrel of a problem in my C++ class that has me
> scratching my head a bit. The professor said we could solicit help from
> any resource we wish, as long as that resource doesn't provide us the
> actual working C++ code for the answer. So, I turn to the tutor list
> with what should prove an interesting minor academic challenge.
>
> If anyone can help me figure out how to do this in Python, that would
> very likely give me a much-appreciated assist. If nothing else, someone
> out there might think this is a really fun thing to do on its own merits.
>
> We have been tasked with writing "a class for an imaginary number" using
> the attached Rational.h file as an example. I don't have any problems
> writing the code itself, but don't really have a comprehensive
> understanding of imaginary numbers. I'm at a bit of a loss as to how to
> perform common operations on them.

Unfortunately [ ;-) ] Python has this complex-type built in, so it would
be
useless - in the highest sense of the word - to implement it on your own
in Python.  So it's most appropriate for you. Just try it!

First you could use Python to explore complex numbers, e. g. this way:

>>> 1j+2j
3j
>>> 1j+2j  # imaginary
3j
>>> (1+3j) + (2-5j)  # complex
(3-2j)
>>> (1+3j) * (2-5j)  # complex
(17+1j)
>>> (1+3j) - (2-5j)  # complex
(-1+8j)
>>> (1+3j) / (2-5j)  # complex
(-0.44827586206896552+0.37931034482758624j)
>>> # Then import complex mathematics
>>> import cmath
>>> # to verify:
>>> cmath.sqrt(-1)
1j
>>> # play around
>>> z = 3+4j
>>> abs(z)
5.0
>>> z.conjugate()
(3-4j)
>>> z.real
3.0
>>> z.imag
4.0
>>>

You may find information about this at:

http://www.python.org/doc/current/lib/typesnumeric.html

An example of how to implement things like these in Python was
posted by Kirby several month ago. It's contained in:

http://mail.python.org/pipermail/tutor/2002-January/011021.html

(It's actually an implementatino of the rationals-class, which is
described in
your
rational.h)

Have fun! (And excuse, that I didn't talk more to you, but I'm sure
there are
lots
of people on this list, who will add ample contributions ....   (hooo,
... my
English!)

Gregor

>
>
> (By the way, I've been taking notes for the C++ class on my laptop and
> coding some of the assignments in both C++ and in Python. I plan to
> bundle all this up for Useless Python soon.)
>
> Rob
> http://uselesspython.com
>
>   ------------------------------------------------------------------------
> // rational.h: declaration of Rational ADT
>
> etc. etc.