// Paweł Rzechonek (c) October 2005
// klasa reprezentująca liczbę zespoloną
// (pola ostateczne, przeciążenie konstruktora, referencja this, składowe statyczne)

package narzedzia;

public class LZesp
{
    public final double re;
    public final double im;

    public LZesp (double re, double im)
    {
        this.re = re;
        this.im = im;
    }
    public LZesp (double re)
    {
        this(re,0);
    }
    public LZesp ()
    {
        this(0);
    }

    public static LZesp zero = new LZesp(0);
    public static LZesp jeden = new LZesp(1);

    public LZesp liczbaPrzeciwna ()
    {
        return new LZesp(-re,-im);
    }
    public LZesp liczbaOdwrotna ()
    {
        double r = re*re+im*im;
        return new LZesp(re/r,-im/r);
    }
    public LZesp liczbaSprzezona ()
    {
        return new LZesp(re,-im);
    }

    public static LZesp suma (LZesp x, LZesp y)
    {
        return new LZesp(x.re+y.re,x.im+y.im);
    }
    public static LZesp roznica (LZesp x, LZesp y)
    {
        return suma(x,y.liczbaPrzeciwna());
    }
    public static LZesp iloczyn (LZesp x, LZesp y)
    {
        return new LZesp(x.re*y.re-x.im*y.im,x.re*y.im+x.im*y.re);
    }
    public static LZesp iloraz (LZesp x, LZesp y)
    {
        return iloczyn(x,y.liczbaOdwrotna());
    }

    public String toString ()
    {
        return "("+re+','+im+")";
    }

    public static LZesp konwertujLZesp (String napis)
    {
        napis = napis.trim();
        int d = napis.length();
        int p = napis.indexOf(',');
        if (d<5) throw new NumberFormatException();
        if (napis.charAt(0)!='(') throw new NumberFormatException();
        if (napis.charAt(d-1)!=')') throw new NumberFormatException();
        if (p==-1) throw new NumberFormatException();
        double r = Double.parseDouble(napis.substring(1,p));
        double i = Double.parseDouble(napis.substring(p+1,d-1));
        return new LZesp(r,i);
    }
}
