complex numbers – the code

// see the last post "using complex numbers" for more details
class Complex{
  float x,y;

  Complex(float xp,float yp){
    x=xp;
    y=yp;
  }

  // addition
    Complex add(Complex two){
    return new Complex(x+two.x,y+two.y);
  }

  // multipliction  
  Complex mult(Complex two){
    return new Complex(x*two.x-y*two.y,x*two.y+y*two.x);
  }

  //  complex conjugation (inverting the sign of the imaginary part)
  Complex cc(){
    return new Complex(x,-y);
  }

  // "inversion"= 1/z
  Complex invers(){
    float rsq=x*x+y*y+1E-10;
    return new Complex(x/rsq,-y/rsq);
  }

  //  n-th power of z  
  Complex pwr(int n){
    Complex result=new Complex(x,y);
    float h;
    for (int i=2;i<=n;i++){
      h=result.x*x-result.y*y;
      result.y=result.y*x+result.x*y;
      result.x=h;
    }
    return result;
  }

  //  absolute value, squared
    float rsq(){
    return x*x+y*y;
  }
}
This entry was posted in programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s