view yetilab/complex.yeti @ 296:ec6a36d88f57

Move complex tests to complex package
author Chris Cannam
date Fri, 31 May 2013 22:02:03 +0100
parents 197d23954a4e
children afce0ab788d1
line wrap: on
line source

module yetilab.complex;

load yetilab.vector.type;
load yetilab.complex.type;

vec = load yetilab.vector;

import java.lang: ClassCastException;

class Cplx(double real, double imag)
    int getReal()
        real,
    int getImag()
        imag,
    double getMagnitude()
        sqrt (real * real + imag * imag),
    double getAngle()
        Math#atan2(imag, real),
    String toString()
        if real == int real and imag == int imag then
            if imag < 0 then
                " \(int real) - \(int (-imag))i"
            else 
                " \(int real) + \(int imag)i"
            fi
        else
            if imag < 0 then
                " \(real) - \((-imag))i"
            else 
                " \(real) + \(imag)i"
            fi
        fi,
    int hashCode()
        Double#valueOf(real)#hashCode() + Double#valueOf(imag)#hashCode(),
    boolean equals(Object other)
        try
            c = other unsafely_as ~Cplx;
            c#getReal() == real and c#getImag() == imag
        catch ClassCastException:
            false
        yrt,
end;

real c1 is ~Cplx -> number =
    c1#getReal();

imaginary c1 is ~Cplx -> number =
    c1#getImag();

complex re im is number -> number -> ~Cplx =
    new Cplx(re, im);

magnitude c is ~Cplx -> number =
    c#getMagnitude();

angle c is ~Cplx -> number =
    c#getAngle();

add c1 c2 is ~Cplx -> ~Cplx -> ~Cplx =
    complex (real c1 + real c2) (imaginary c1 + imaginary c2);

scale r c is number -> ~Cplx -> ~Cplx =
    complex (r * real c) (r * imaginary c);

zeros n is number -> array<~Cplx> =
    array (map \(complex 0 0) [1..n]);

magnitudes cc is list?<~Cplx> -> vector =
    vec.fromList (map magnitude cc);

angles cc is list?<~Cplx> -> vector =
    vec.fromList (map angle cc);

{
   real,
   imaginary,
   complex,
   magnitude,
   angle,
   add,
   scale,
   zeros,
   magnitudes,
   angles,
} as {
   real is cplx -> number,
   imaginary is cplx -> number,
   complex is number -> number -> cplx,
   magnitude is cplx -> number,
   angle is cplx -> number,
   add is cplx -> cplx -> cplx,
   scale is number -> cplx -> cplx,
   zeros is number -> array<cplx>,
   magnitudes is list?<cplx> -> vector,
   angles is list?<cplx> -> vector,
}