Numeri complessi C#
Rispetto al Java, in C# è possibile utilizzare le proprietà (con get e set) e l'overload degli operatori, così da ottenere un uso più chiaro e immediato della classe. Complexsharp.zip (14 kb)
Il file zip contiene un progetto di esempio con l'implementazione della classe. // Classe per la definizione di numeri complessi con relative operazioni matematiche. public class Complex { // Membri e proprietà public double Re,Im; public double Abs // modulo { get { return Math.Sqrt(Math.Pow(this.Re,2)+Math.Pow(this.Im,2)); } set { double arg = this.Arg; this.Re = value*Math.Cos(arg); this.Im = value*Math.Sin(arg); } } public double Arg // fase { get { return Math.Atan2(this.Im,this.Re); } set { double abs = this.Abs; this.Re = abs*Math.Cos(value); this.Im = abs*Math.Sin(value); } } // Modifica contemporaneamente modulo e fase public void SetPolar(double abs,double arg) { this.Re=abs*Math.Cos(arg); this.Im=abs*Math.Sin(arg); } // Costruttori public Complex(double a,double b,bool Polar) { // Se Polar=false a e b sono parte reale e immaginaria if(!Polar) { this.Re=a; this.Im=b; } // Se Polar=true a e b sono modulo e fase else { this.Re=a*Math.Cos(b); this.Im=a*Math.Sin(b); } } public Complex(double a,double b): this(a,b,false) { }
// Visualizzazione con stringa public string ToString(bool Polar) { string str; if(!Polar) { str=String.Format("{0} {1} {2} i",this.Re,(this.Im<0)?"-":"+",Math.Abs(this.Im)); } else { str=String.Format("{0} con fase {1}",this.Abs,this.Arg); } return str; } // Sovrascrive la funzione ToString() predefinita public override string ToString() { return this.ToString(false); } // Operatori e altre funzioni matematiche public static Complex operator +(Complex a,Complex b) { return new Complex(a.Re+b.Re,a.Im+b.Im); } public static Complex operator -(Complex z) { return new Complex(-z.Re,-z.Im); } public static Complex operator -(Complex a, Complex b) { return new Complex(a.Re-b.Re,a.Im-b.Im); } public static Complex operator *(Complex a,Complex b) { return new Complex(a.Re*b.Re-a.Im*b.Im,a.Im*b.Re+a.Re*b.Im); } public static Complex operator ~(Complex z) // coniugato { return new Complex(z.Re,-z.Im); } public static Complex operator /(Complex a,Complex b) { Complex w=a*~b; double t=(Math.Pow(b.Re,2)+Math.Pow(b.Im,2)); return new Complex(w.Re/t,w.Im/t); } public static Complex Pow(Complex z,int n) // potenza n-esima { return new Complex(Math.Pow(z.Abs,n),n*z.Arg,true); } public static Complex[] Root(Complex z,int n) // radici n-esime { Complex[] roots=new Complex[n]; for(int k=0;k<N;K++) { roots[k]=new Complex(Math.Pow(z.Abs,1/(double)n),(z.Arg+2*k*Math.PI)/n,true); } return roots; } } |
|