[Tutor] imaginary number class

Kirby Urner urnerk@qwest.net
Tue, 25 Jun 2002 12:41:27 -0400


As others have pointed out, Python includes a complex number facility, but not
a rational number facility, so you find more people writing the latter in 
Python than the former.  But you could do complex numbers if you wanted.

Like a Rational class, with a,b as numerator,denominator, you'd want to
define instance members a,b for complex number (a,b), which is the same
as a + bj (using j in place of i).  The structure of the Python class 
would look something like:

   class Complex:

      self.__init__(self,a,b):
         self.a = a
         self.b = b

      self __add__(self,other):
         return Complex(self.a + other.a, self.b + other.b)

      self __sub__(self,other):
         # etc. etc.

      self __mul__(self,other):
        # using Alan's (3+4j)(5+6j) = 3*5+4j*5+3*6j+4j*6j        
        return Complex(self.a*other.a - self.b*other.b,
                       self.b*other.a + self.a*other.b)

      self __div__(self,other):
        # check Alan's other example
        # etc. etc.

You could write these methods in Python, and then translate them to 
a C++ class (don't worry, only the standard framework provided, with
no working guts):

=====
// complex.h
#ifndef COMPLEX_H
#define COMPLEX_H

// the class (defines the API)

   class Complex {
          double a,b; // private variables
       public:          
          Complex(double s, double t){a=s;b=t;};  //e.g. Python __init__
          Complex operator+(const Complex& other) const; // __add__
          Complex operator*(const Complex& other) const; // __mul__
          etc. etc.
   };

#endif

=====
// complex.cpp
#include "complex.h"

/* implementations (may actually be hidden in compiled source)
   -- in any case distinct from the header
*/

Complex Complex::operator+(const Complex& other) const { etc. } 
Complex Complex::operator*(const Complex& other) const { etc. }

=====
// test.cpp
#include "complex.h"

int main(){
  Complex c1(3.0 , 5.0); // same as c1 = Complex(3.0, 5.0) in Python
  Complex c2(4.0 ,-9.0);
  Complex c3 = c1 + c2;
}

=====

Note that in C++, unlike in Python, the guts of a class are typically 
defined in a file separate from the class, which is put in the header
with prototypes only (as a guide to client programmers).  

Both allow Python and C++ support operator overriding (not Java).  
Python has just the one constructor (__init__) whereas in C++, like 
in Java, you can overload functions (including the constructor) 
simply by changing the signature (args and return type).  

Also, in Python, we typically don't put so much emphasis on making 
variable properties private (using name mangling), although we might 
define __setattr__ in some cases (to protect how/what data goes in):

 >>> class Test(object):
	def __init__(self,a):
		self.__dict__['a'] = a
	def __setattr__(self,attr,b):
		print "Wow!"
		self.__dict__[attr] = b

 >>> ot = Test(1)
 >>> ot.a
 1
 >>> ot.a = 2
 Wow!
 >>> ot.a
 2

Lots of web pages on complex numbers out there.  You need to decide
what the list of methods you want to implement might be, e.g. do you
want to be able to raise Complex numbers to powers?  How about to 
complex powers? (yech).  Can Python raise complex numbers to complex
powers?  Indeed it can:

 >>> from cmath import *
 >>> pow(1j,1j)
 (0.20787957635076193+0j)  # note that j to the j is a real number!

Kirby

On Tue, 25 Jun 2002 10:04:58 -0500
"Rob Andrews" <rob@uselesspython.com> wrote:

> 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.
> 
> (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
>