public static final Cmplx div(Cmplx a, Cmplx b) { Cmplx c = new Cmplx(); double r, den; if (Math.abs(b.r) >= Math.abs(b.i)) { r = b.i / b.r; den = b.r + r * b.i; c.r = (a.r + r * a.i) / den; c.i = (a.i - r * a.r) / den; } else { r = b.r / b.i; den = b.i + r * b.r; c.r = (a.r * r + a.i) / den; c.i = (a.i * r - a.r) / den; } return c; }
/** creates a unit mag complex number. zero is assigned (1,0) */ public final Cmplx unitVector() { double mag = mag(); if (mag != 0) { return Cmplx.div(this, mag); } else { return new Cmplx(1, 0); } }
public final Cmplx sqrt() { Cmplx c = new Cmplx(); double x, y, w, r; if ((this.r == 0.0) && (this.i == 0.0)) { c.r = (c.i = 0.0); return (c); } else { x = Math.abs(this.r); y = Math.abs(this.i); if (x >= y) { r = y / x; w = Math.sqrt(x) * Math.sqrt(0.5 * (1.0 + Math.sqrt(1.0 + r * r))); } else { r = x / y; w = Math.sqrt(y) * Math.sqrt(0.5 * (r + Math.sqrt(1.0 + r * r))); } if (this.r >= 0.0) { c.r = w; c.i = this.i / (2.0 * w); } else { c.i = (this.i >= 0.0) ? w : -w; c.r = this.i / (2.0 * c.i); } return (c); } }
/** * Computes the correlation of fdata with gdata. The value of the output at index i is the sum * over j of fdata[i+j]*gdata[j], although using the FFT is much faster than direct sum. * * @see http://www.ulib.org/webRoot/Books/Numerical_Recipes/bookcpdf.html section 13-2 */ public static final float[] correlate(float[] fdata, float[] gdata) { if (fdata.length != gdata.length) { throw new IllegalArgumentException( "fdata and gdata must have same length. " + fdata.length + " " + gdata.length); } Cmplx[] fTrans = fft(fdata); Cmplx[] gTrans = fft(gdata); for (int i = 0; i < fTrans.length; i++) { fTrans[i] = Cmplx.mul(fTrans[i], gTrans[i].conjg()); } // end of for (int i=0; i<gdata.length; i++) return fftInverse(fTrans, fdata.length); }
public static final Cmplx mul(Cmplx a, Cmplx b) { Cmplx c = new Cmplx(); c.r = a.r * b.r - a.i * b.i; c.i = a.i * b.r + a.r * b.i; return c; }
public static final Cmplx mul(Cmplx a, double b) { return Cmplx.mul(a, new Cmplx(b, 0)); }
public static final Cmplx mul(double a, Cmplx b) { return Cmplx.mul(new Cmplx(a, 0), b); }
public static final Cmplx sub(Cmplx a, Cmplx b) { Cmplx c = new Cmplx(); c.r = a.r - b.r; c.i = a.i - b.i; return c; }
public static final Cmplx sub(Cmplx a, double b) { return Cmplx.sub(a, new Cmplx(b, 0)); }
public static final Cmplx sub(double a, Cmplx b) { return Cmplx.sub(new Cmplx(a, 0), b); }
public static final Cmplx add(Cmplx a, Cmplx b) { Cmplx c = new Cmplx(); c.r = a.r + b.r; c.i = a.i + b.i; return c; }
public static final Cmplx exp(Cmplx arg) { Cmplx c = new Cmplx(); c.r = Math.exp(arg.r) * Math.cos(arg.i); c.i = Math.exp(arg.r) * Math.sin(arg.i); return c; }
public final Cmplx conjg() { Cmplx c = new Cmplx(); c.r = this.r; c.i = -this.i; return c; }