public static Matrix CalculatGivensRotation(Complex a, Complex b) { Complex c, s, r; r = ComplexMath.Sqrt(a.Conjugate() * a + b.Conjugate() * b); if (b == 0) { c = 1; s = 0; } else if (a == 0) { c = 0; s = ComplexMath.Sign(b.Conjugate()); } else { c = a.Abs() / r; s = ComplexMath.Sign(a) * b.Conjugate() / r; } Matrix givensRot = new Matrix(2); givensRot[0, 0] = c; givensRot[0, 1] = s; givensRot[1, 0] = -s.Conjugate(); givensRot[1, 1] = c; return givensRot; }
/// <summary> /// Test complex number type. /// </summary> /// <remarks> /// PASSING 10/17/2015 /// </remarks> private static void ComplexNumTests() { Complex c1 = 1, c2 = 0, c3 = Complex.Unit; Complex c4 = new Complex(2, 2); Complex c5 = new Complex(2, -4); Complex c6 = new Complex(5, 5); Complex c7 = new Complex(3, 9); Debug.Print("Float 1 becomes: " + c1); Debug.Print("Float 0 becomes: " + c2); Debug.Print("Unit Complex is: " + c3); Debug.Print("The conjugate of " + c4 + " is " + c4.Conjugate()); Debug.Print("Magnitude and Phase of " + c4 + " are " + c4.Magnitude + " and " + c4.Phase + " radians"); Debug.Print(c4 + " + " + c5 + " is " + (c4 + c5)); Debug.Print(c6 + " * 2 is " + (c6 * 2)); Debug.Print(c6 + " / 5 is " + (c6 / 5)); Debug.Print(c6 + " * " + c4 + " is " + (c6 * c4) + " with phase " + ((c6 * c4).Phase * (180 / System.Math.PI)) + " degrees"); Debug.Print(c7 + " + 3 is " + (c7 + 3)); }
public unsafe Complex GetOutput(int x, int y) { bool conj = false; if (y > this._mHeight) { y = (int)(2 * this._mHeight) - y; x = (int)this._width - x - 1; conj = true; } long index = x * this._mHeight + y; var ptr = (Complex *)this._out.ToPointer(); Complex RetVal = ptr[index]; if (conj) { RetVal = Complex.Conjugate(RetVal); } return(RetVal); }
/// <summary>Performs a rank-1 update (conjuaged) of a general matrix, i.e. A := \alpha * x * conj(y^t) + A. /// </summary> /// <param name="m">The number of rows of matrix A.</param> /// <param name="n">The number of columns of matrix A.</param> /// <param name="alpha">The scalar \alpha.</param> /// <param name="x">The vector x with at least 1 + (<paramref name="m" />-1) * |<paramref name="incX" />| elements.</param> /// <param name="y">The vector y with at least 1 + (<paramref name="n" />-1) * |<paramref name="incY" />| elements.</param> /// <param name="a">The matrix A of dimension (<paramref name="lda" />, <paramref name="n" />) supplied column-by-column.</param> /// <param name="lda">The leading dimension of <paramref name="a" />, must be at least max(1,<paramref name="m" />).</param> /// <param name="incX">The increment for the elements of <paramref name="x" />.</param> /// <param name="incY">The increment for the elements of <paramref name="y" />.</param> public void zgerc(int m, int n, Complex alpha, Complex[] x, Complex[] y, Complex[] a, int lda, int incX = 1, int incY = 1) { if (m == 0 || n == 0 || alpha == 0.0) { return; } int jy = 0; int kx = 0; for (int j = 0; j < n; j++) { Complex temp = alpha * Complex.Conjugate(y[jy]); int ix = kx; for (int i = 0; i < m; i++) { a[i + j * lda] += x[ix] * temp; ix += incX; } jy += incY; } }
/// <summary> /// 1次元IFFT /// </summary> public static void IFFT( int bitSize, Complex[] input, out double[] outputReal ) { int dataSize = 1 << bitSize; Complex[] output = new Complex[dataSize]; outputReal = new double[dataSize]; //複素共役をとってfft for (int i = 0; i < dataSize; i++) { input[i] = Complex.Conjugate(input[i]); } FFT(bitSize, input, out output); for (int i = 0; i < dataSize; i++) { outputReal[i] = Complex.Conjugate(output[i]).Real / (double)dataSize; } }
public static Complex gamma_L(TwoPortNetworks.TwoPortNetwork tpn) { if (tpn.state != TwoPortNetworks.STATE.S) { throw new Exception("Error: Attempt to call s-param function without two-port network in s-params mode"); } Complex dd = tpn.det(); Complex B2 = 1 + Math.Pow(Complex.Abs(tpn.p[1, 1]), 2) - Math.Pow(Complex.Abs(tpn.p[0, 0]), 2) - Math.Pow(Complex.Abs(dd), 2); Complex C2 = tpn.p[1, 1] - dd * Complex.Conjugate(tpn.p[0, 0]); Complex numer1 = B2 + Complex.Sqrt(Complex.Pow(B2, 2) - 4 * Complex.Pow(Complex.Abs(C2), 2)); Complex denom1 = 2 * C2; Complex g1 = numer1 / denom1; Complex numer2 = B2 - Complex.Sqrt(Complex.Pow(B2, 2) - 4 * Complex.Pow(Complex.Abs(C2), 2)); Complex denom2 = 2 * C2; Complex g2 = numer2 / denom2; return(g1.Magnitude < 1 ? g1 : g2); }
public void Run() { var a = new Complex(5.0, 6.0); var b = new Complex(-3.0, 4.0); Console.WriteLine("a = " + a); Console.WriteLine("b = " + b); Console.WriteLine("Re(a) = " + a.Re()); Console.WriteLine("Im(a) = " + a.Im()); Console.WriteLine("b + a = " + b.Plus(a)); Console.WriteLine("a - b = " + a.Minus(b)); Console.WriteLine("a * b = " + a.Times(b)); Console.WriteLine("b * a = " + b.Times(a)); Console.WriteLine("a / b = " + a.Divides(b)); Console.WriteLine("(a / b) * b = " + a.Divides(b).Times(b)); Console.WriteLine("conj(a) = " + a.Conjugate()); Console.WriteLine("|a| = " + a.Abs()); Console.WriteLine("tan(a) = " + a.Tan()); Console.ReadLine(); }
public Complex[][] Create() { var result = new float[Size][]; var complexResult = new Complex[Size][]; float max = 0; for (var i = 0; i < Size; i++) { result[i] = new float[Size]; complexResult[i] = new Complex[Size]; for (var j = 0; j < Size; j++) { var parameter = new PhillipsParameter { K = new K { Kx = (float)(2.0 * Math.PI / Size) * (-Size / 2 + i), Ky = (float)(2.0 * Math.PI / Size) * (-Size / 2 + j) }, WindDirection = new WindDirection { X = 1, Y = 0.7f }, WindSpeed = 10000, G = (float)9.81, A = 100 }; complexResult[i][j] = CalculateH0(PhillipsSpectrum(parameter)); complexResult[i][j] += Complex.Conjugate(complexResult[i][j]); } } return(complexResult); }
private void Mirror() { int maxImagineryValue = -1; int minImaginaryValue = 25; for (int i = 0; i < PresentShape.Coords.Length; i++) { if (maxImagineryValue < PresentShape.Coords[i].Imaginary) { maxImagineryValue = (int)PresentShape.Coords[i].Imaginary; } else if (minImaginaryValue > PresentShape.Coords[i].Imaginary) { minImaginaryValue = (int)PresentShape.Coords[i].Imaginary; } } for (int i = 0; i < PresentShape.Coords.Length; i++) { if (PresentShape.Coords[i].Imaginary >= 0) { Draw.One(' ', (int)PresentShape.Coords[i].Real, (int)PresentShape.Coords[i].Imaginary); } PresentShape.Coords[i] = Complex.Conjugate(PresentShape.Coords[i]); PresentShape.Coords[i] = Complex.Add(PresentShape.Coords[i], (minImaginaryValue + maxImagineryValue + 1) * Complex.ImaginaryOne); } for (int i = 0; i < PresentShape.Coords.Length; i++) { if (PresentShape.Coords[i].Imaginary >= 0) { Draw.One(PresentShape.ShapePattern, (int)PresentShape.Coords[i].Real, (int)PresentShape.Coords[i].Imaginary); } } _pressedkey = new ConsoleKeyInfo(); }
private void PrepareRFunction(Complex[] zeta0) { var nx = Model.Anomaly.LocalSize.Nx; var ny = Model.Anomaly.LocalSize.Ny; var nz = Model.Nz; var conjZBkg = new Complex[nz]; var sqrtReZetaBkg = new Complex[nz]; var zetas = Model.Anomaly.Zeta; for (int k = 0; k < nz; k++) { var zetaBkg = zeta0[k]; conjZBkg[k] = Complex.Conjugate(zetaBkg); sqrtReZetaBkg[k] = Complex.Sqrt(zetaBkg.Real); } long index = 0; for (int i = 0; i < nx; i++) { for (int j = 0; j < ny; j++) { for (int k = 0; k < nz; k++) { var zeta = zetas[i, j, k]; if (_operatorType == OperatorType.Chi0) { _rFunction[index++] = sqrtReZetaBkg[k] / (zeta + conjZBkg[k]); } if (_operatorType == OperatorType.A) { _rFunction[index++] = (zeta - zeta0[k]) / (zeta + conjZBkg[k]); } } } } }
public static PointPairList PerfectFilterNoise(PointPairList i_g, PointPairList i_h, double alpha) { var g = ListToComplex(i_g); var h = ListToComplex(i_h); var btw = g.Count - h.Count; if (h.Count < g.Count) { for (var i = 0; i < btw; i++) { h.Add(new Complex(0, 0)); } } g = GetSpectre(g); h = GetSpectre(h, false); for (var i = 0; i < h.Count; i++) { g[i] = Complex.Conjugate(h[i]) / (Complex.Pow(Complex.Abs(h[i]), 2) + alpha * alpha) * g[i]; } return(ComplexToPointPairList(ReverseSpectre(g))); }
public static void RunTests_One() { // Verify real part is 1.0, and imaginary part is 0.0 Support.VerifyRealImaginaryProperties(Complex.One, 1.0, 0.0, "Verify real part is 1.0, and imaginary part is 0.0"); // verify magnitude is 1.0 and phase is 0.0. Support.VerifyMagnitudePhaseProperties(Complex.One, 1.0, 0.0, "Verify magnitude is 1.0, and phase is 0.0"); // create a complex number with random real and imaginary parts double realPart = Support.GetRandomDoubleValue(false); double imaginaryPart = Support.GetRandomDoubleValue(false); Complex complexRandom = new Complex(realPart, imaginaryPart); // verify x*1 = x Complex multResult = complexRandom * Complex.One; Assert.True(multResult == complexRandom, string.Format("Mult with 1 does not equal to complex:{0} itself: {1}", complexRandom, multResult)); // verify x/1 = x Complex divisorOneResult = complexRandom / Complex.One; Assert.True(divisorOneResult == complexRandom, string.Format("Division by 1 does not equal to complex:{0} itself: {1}", complexRandom, divisorOneResult)); // verify Abs(1) = 1 double absResult = Complex.Abs(Complex.One); Assert.True(1.0 == absResult, string.Format("Abs(One) does not equal to 1: {0}", absResult)); // verify Conjugate(1) = 1 Complex conjugateResult = Complex.Conjugate(Complex.One); Assert.True(Complex.One == conjugateResult, string.Format("Conjugate(One) does not equal to One: {0}", conjugateResult)); // verify Reciprocal(1) = 1 Complex reciprocalResult = Complex.Reciprocal(Complex.One); Assert.True(Complex.One == reciprocalResult, string.Format("Reciprocal(One) does not equal to One: {0}", reciprocalResult)); }
/// <summary> /// imgにpatが含まれているか調査します。 /// </summary> /// <param name="img"></param> /// <param name="pat"></param> /// <returns></returns> public double FastZNCC(ref Complex[][] img, ref Complex[][] pat) { if (img.Length < pat.Length || img[0].Length < pat[0].Length) { throw new ArgumentException("pat must be smaller than img."); } /// <summary> /// 未着手 /// </summary> Complex[][] imgFFT = FFT2D(ref img); Complex[][] patFFT = FFT2D(ref pat); // Combolution for (int nx = 0; nx < imgFFT.Length; ++nx) { for (int ny = 0; ny < imgFFT[0].Length; ++ny) { imgFFT[nx][ny] = imgFFT[nx][ny] * Complex.Conjugate(patFFT[nx][ny]); } } return(1); }
static void FFT_rec(ref Complex[] data, bool IsInverseTransform) { if (data.Length <= 1) { return; } Complex[] dataEven = new Complex[data.Length / 2]; Complex[] dataOdd = new Complex[data.Length / 2]; for (int i = 0; i < data.Length;) { dataEven[i / 2] = data[i++]; dataOdd[i / 2] = data[i++]; } FFT_rec(ref dataEven, IsInverseTransform); FFT_rec(ref dataOdd, IsInverseTransform); for (int i = 0; i < data.Length / 2; ++i) { Complex phi = new Complex(Math.Cos(-2 * Math.PI * i / data.Length), Math.Sin(-2 * Math.PI * i / data.Length)); Complex t = dataOdd[i] * (IsInverseTransform ? Complex.Conjugate(phi) : phi); data[i] = dataEven[i] + t; data[data.Length / 2 + i] = dataEven[i] - t; } }
public void Run() { var a = new Complex(5.0, 6.0); var b = new Complex(-3.0, 4.0); Console.WriteLine("a = " + a); Console.WriteLine("a = " + a.ToExponentials()); Console.WriteLine("b = " + b); Console.WriteLine("b = " + b.ToExponentials()); Console.WriteLine("Re(a) = " + a.Re()); Console.WriteLine("Im(a) = " + a.Im()); Console.WriteLine("b + a = " + b.Plus(a)); Console.WriteLine("a - b = " + a.Minus(b)); Console.WriteLine("a * b = " + a.Times(b)); Console.WriteLine("b * a = " + b.Times(a)); Console.WriteLine("a / b = " + a.Divides(b)); Console.WriteLine("(a / b) * b = " + a.Divides(b).Times(b)); Console.WriteLine("conj(a) = " + a.Conjugate()); Console.WriteLine("|a| = " + a.Abs()); Console.WriteLine("tan(a) = " + a.Tan()); Console.ReadLine(); }
public static Complex[] GetCorrelationWithFFT(Complex[] originalVector, Complex[] correlationVector) { if (originalVector.Length != correlationVector.Length) { throw new ArgumentException("Different length of vectors"); } CorrelationComplexibilityWithFFT = 0; // ReSharper disable once InconsistentNaming var originalVectorWithFFT = FourierTransformUtils.MakeFFT(originalVector, TransformDirection.Direct); CorrelationComplexibilityWithFFT += FourierTransformUtils.Complexibility; var correlationVectorWithFFT = FourierTransformUtils.MakeFFT(correlationVector, TransformDirection.Direct); CorrelationComplexibilityWithFFT += FourierTransformUtils.Complexibility; var result = originalVectorWithFFT.Zip(correlationVectorWithFFT, (x, y) => Complex.Conjugate(x) * y).ToArray(); return(FourierTransformUtils.MakeFFT(result, TransformDirection.Reverse)); }
private static void VerifyReciprocal(Double real, Double imaginary) { // Create complex numbers Complex c_test = new Complex(real, imaginary); Complex c_rcp = Complex.Reciprocal(c_test); Complex c_expected = Complex.Zero; if (Complex.Zero != c_test && !(Double.IsInfinity(real) && !(Double.IsInfinity(imaginary) || Double.IsNaN(imaginary))) && !(Double.IsInfinity(imaginary) && !(Double.IsInfinity(real) || Double.IsNaN(real)))) { Double magnitude = c_test.Magnitude; c_expected = (Complex.Conjugate(c_test) / magnitude); // in order to avoid Infinity = magnitude* magnitude c_expected = c_expected / magnitude; } if (false == Support.VerifyRealImaginaryProperties(c_rcp, c_expected.Real, c_expected.Imaginary)) { Console.WriteLine("Error_rye102!!! Reciprocal({0})", c_test); Assert.True(false, "Verification Failed"); } }
/// <summary> /// Create a random symmetric sparse matrix. /// </summary> /// <param name="size">The size of the matrix.</param> /// <param name="density">The density (between 0.0 and 1.0).</param> /// <param name="random">The random source.</param> /// <returns>Random sparse matrix.</returns> public static SparseMatrix RandomSymmetric(int size, double density, Random random) { // Number of non-zeros per row. int nz = (int)Math.Max(size * size * density, 1d); var C = new CoordinateStorage <Complex>(size, size, nz); int m = (nz - size) / 2; for (int k = 0; k < m; k++) { int i = (int)Math.Min(random.NextDouble() * size, size - 1); int j = (int)Math.Min(random.NextDouble() * size, size - 1); Complex value = random.NextDouble(); if (i != j) { // Add imaginary part only for non-diagonals. value = new Complex(value.Real, random.NextDouble()); } if (i != j) { C.At(i, j, value); C.At(j, i, Complex.Conjugate(value)); } } // Fill diagonal. for (int i = 0; i < size; i++) { C.At(i, i, random.NextDouble()); } return((SparseMatrix)C.ToSparseMatrix()); }
private void GetKernelFourier(Complex[,] kernelFourier) { int length = kernelFourier.Length; // Kernel length = height*width int n0 = kernelFourier.GetLength(0); // Kernel height int n1 = kernelFourier.GetLength(1); // Kernel width switch (_filterMode) { case FilterMode.FilterKernel: Copy(_filterKernel, kernelFourier); break; case FilterMode.FilterSize: Fill(kernelFourier, _filterSize, Complex.One); break; case FilterMode.FilterStep: int filterStep = _filterStep; var filterSize = new Size(MulDiv(n1, 1, filterStep + 1), MulDiv(n0, 1, filterStep + 1)); Fill(kernelFourier, filterSize, Complex.One); break; default: throw new NotImplementedException(); } Fourier(kernelFourier, FourierDirection.Forward); for (int i = 0; i < n0; i++) { for (int j = 0; j < n1; j++) { Complex value = kernelFourier[i, j]; value = Complex.Pow(value * Complex.Conjugate(value), _filterPower / 2); kernelFourier[i, j] = value; } } }
/// <summary> /// Apply the ith Householder vector to x. /// </summary> static bool ApplyHouseholder(SparseMatrix V, int i, double beta, Complex[] x) { int p; Complex tau = Complex.Zero; if (x == null) { return(false); // check inputs } int[] Vp = V.p; int[] Vi = V.i; Complex[] Vx = V.x; for (p = Vp[i]; p < Vp[i + 1]; p++) // tau = v'*x { tau += Complex.Conjugate(Vx[p]) * x[Vi[p]]; } tau *= beta; // tau = beta*(v'*x) for (p = Vp[i]; p < Vp[i + 1]; p++) // x = x - v*tau { x[Vi[p]] -= Vx[p] * tau; } return(true); }
// Verification is done with Abs and Conjugate methods private static void VerifyBinaryDivideResult(double realFirst, double imgFirst, double realSecond, double imgSecond) { // Create complex numbers Complex cFirst = new Complex(realFirst, imgFirst); Complex cSecond = new Complex(realSecond, imgSecond); Complex cExpectedResult = (cFirst * Complex.Conjugate(cSecond)); double cExpectedReal = cExpectedResult.Real; double cExpectedImaginary = cExpectedResult.Imaginary; if (!double.IsInfinity(cExpectedReal)) { cExpectedReal = cExpectedReal / (cSecond.Magnitude * cSecond.Magnitude); } if (!double.IsInfinity(cExpectedImaginary)) { cExpectedImaginary = cExpectedImaginary / (cSecond.Magnitude * cSecond.Magnitude); } // local variables Complex cResult; // arithmetic binary divide operation cResult = cFirst / cSecond; // verify the result Support.VerifyRealImaginaryProperties(cResult, cExpectedReal, cExpectedImaginary, string.Format("Binary Divide test = ({0}, {1}) / ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); // arithmetic divide (static) operation cResult = Complex.Divide(cFirst, cSecond); // verify the result Support.VerifyRealImaginaryProperties(cResult, cExpectedReal, cExpectedImaginary, string.Format("Divide (Static) test = ({0}, {1}) / ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); }
public override double F(List <double> x) { throw new NotImplementedException(); Complex[] p = new Complex[n]; int p_conj = (int)(2 * Math.Floor((double)n / 2)); for (int i = 0; i < p_conj; i++) { p[2 * i] = Complex.FromPolarCoordinates(x[2 * i], x[2 * i + 1] * Math.PI * 2); p[2 * i + 1] = Complex.Conjugate(p[i]); } for (int i = 0; i < n - p_conj; i++) { p[i + p_conj] = x[p_conj + i]; } Complex[] a; P2poly(p, out a ); Complex[] Spectrum_Mod = new Complex[Spectrum.Length]; for (int i = 0; i < Spectrum.Length; i++) { Complex denom = 0; Complex s = Complex.ImaginaryOne * freq[i] * Utilities.Numerics.PiX2; Complex Spow = s; for (int j = n - 1; j >= 0; i++) { denom += a[j] * Spow; Spow *= s; } Spectrum_Mod[i] = Spectrum[i] * denom; } //TODO: find a polynomial fit operation that works on complex numbers... //MathNet.Numerics.Fit.Polynomial(freq, Spectrum_Mod, 3); }
/// <summary> /// Solves an upper triangular system L'x=b where x and b are dense. x=b on /// input, solution on output. /// </summary> /// <param name="L">column-compressed, lower triangular matrix</param> /// <param name="x">size n, right hand side on input, solution on output</param> /// <returns>true if successful, false on error</returns> public static bool SolveLt(SparseMatrix L, Complex[] x) { if (x == null) { return(false); // check inputs } int n = L.n; int[] Lp = L.p; int[] Li = L.i; Complex[] Lx = L.x; int p; for (int j = n - 1; j >= 0; j--) { for (p = Lp[j] + 1; p < Lp[j + 1]; p++) { x[j] -= Complex.Conjugate(Lx[p]) * x[Li[p]]; } x[j] /= Complex.Conjugate(Lx[Lp[j]]); } return(true); }
// Стоит переделать public Complex[][] CalculateDotProduct2DArray(int x0, int y0, int width, int height, NearFieldType type) { Complex[][] roi_en_matrix; NearField[] fields; if (type == NearFieldType.Incident) { fields = x_basisNF; } else { fields = y_basisNF; } roi_en_matrix = new Complex[fields.Length][]; for (int i = 0; i < fields.Length; i++) { roi_en_matrix[i] = new Complex[fields.Length]; } for (int i = 0; i < fields.Length; i++) { roi_en_matrix[i] = new Complex[fields.Length]; for (int j = 0; j <= i; j++) { roi_en_matrix[i][j] = fields[i].DotProduct(fields[j], x0, y0, width, height); if (i != j) { roi_en_matrix[j][i] = Complex.Conjugate(roi_en_matrix[i][j]); } } } return(roi_en_matrix); }
public static double[] RealFastFourierTransform(Complex[] src, double amplitude = 1.0) { int n4 = 1 << (Mt.Log2Int(src.Length) - 1); int n = n4 * 4, n2 = n4 * 2, n3 = n4 * 3; int n2mask = n2 - 1; Complex[] Data = new Complex[n2]; TriangularTable Triangle = TriangularTable.Get(n); for (int i = n4; i >= 0; --i) { int j = n2 - i; Complex g1 = src[i]; Complex g2 = Complex.Conjugate(src[j]); Complex h1 = (g1 + g2); Complex h2 = (g1 - g2) * Triangle.Complex(n4 + i); Data[i] = (h1 + h2); Data[j & n2mask] = Complex.Conjugate(h1 - h2); } Data = FastFourierTransform_(Data, false); LetMul(Data, amplitude / n); double[] Dst = New.Array(n, i => (i & 1) == 0 ? Data[i / 2].Real : Data[i / 2].Imaginary); return(Dst); }
/// <summary> /// Solves a lower triangular system U'x=b, where x and b are dense vectors. /// The diagonal of U must be the last entry of each column. ///</summary> /// <param name="U">upper triangular matrix in column-compressed form</param> /// <param name="x">size n, right hand side on input, solution on output</param> /// <returns>true if successful, false on error</returns> public static bool SolveUt(SparseMatrix U, Complex[] x) { if (x == null) { return(false); // check inputs } int n = U.n; int[] Up = U.p; int[] Ui = U.i; Complex[] Ux = U.x; int p; for (int j = 0; j < n; j++) { for (p = Up[j]; p < Up[j + 1] - 1; p++) { x[j] -= Complex.Conjugate(Ux[p]) * x[Ui[p]]; } x[j] /= Complex.Conjugate(Ux[Up[j + 1] - 1]); } return(true); }
//public static Complex[] SpectrumFromIIR(Complex[] a, Complex[] b, int fs = 44100, int n = 512) //{ // double[] ad = new double[a.Length], bd = new double[b.Length]; // for (int i = 0; i < a.Length; i++) ad[i] = a[i].Magnitude; // for (int i = 0; i < b.Length; i++) bd[i] = b[i].Magnitude; // return SpectrumFromIIR(ad, bd, fs, n); //} //public static Complex[] SpectrumFromIIR(double[] a, double[] b, int fs = 44100, int n = 512) //{ // int k = Math.Max(b.Length, a.Length); // double[] f = new double[n]; // for (int i = 0; i < n; i++) f[i] = (double)fs * i / (2 * n); // int pad_sz = n * (int)Math.Ceiling((double)k / n); // Array.Resize(ref b, 2 * n); // Array.Resize(ref a, 2 * n); // Complex[] h = new Complex[n]; // Complex[] pb = FFT_General(b, 0); // Complex[] pa = FFT_General(a, 0); // for (int i = 0; i < h.Length; i++) h[i] = pb[i] / pa[i]; // return h; //} public static Complex[] AutoCorrelation_Coef(Complex[] X, int maxlag) { Complex[] r_l = new Complex[maxlag]; for (int lag = 1; lag <= maxlag; lag++) { Complex mean = 0; for (int i = 0; i < X.Length; i++) { mean += X[i]; } mean /= X.Length; Complex denom = 0; Complex num = 0; int N_k = X.Length - lag; for (int i = 0; i < N_k; i++) { Complex x_X = X[i] - mean; denom += x_X * x_X; num += x_X * Complex.Conjugate(X[i + lag] - mean); } for (int i = 0; i < lag; i++) { int idx = N_k + i; Complex x_X = X[idx] - mean; denom += x_X * x_X; } r_l[lag - 1] = num / denom; } return(r_l); }
private void PerformGivensRotation(Matrix Q, Matrix R, int i, int j, ref Complex Gii, ref Complex Gij, ref Complex Gji, ref Complex Gjj) { // do matrix multiplication by hand for speed for (int k = 0; k < R.Columns; k++) { Complex Rik = R[i, k], Rjk = R[j, k]; R[i, k] = Gii * Rik + Gij * Rjk; R[j, k] = Gji * Rik + Gjj * Rjk; } Complex GTii = Gii.Conjugate(), GTij = Gji.Conjugate(), GTji = Gij.Conjugate(), GTjj = Gjj.Conjugate(); for (int k = 0; k < Q.Rows; k++) { Complex Qki = Q[k, i], Qkj = Q[k, j]; Q[k, i] = Qki * GTii + Qkj * GTji; Q[k, j] = Qki * GTij + Qkj * GTjj; } }
private void calculate() { List <double> e = new List <double>(); for (int i = 0; i < vectorLength; i++) { // abs(s11*conj(s21)+s12*conj(s22))/(sqrt((1-abs(s11)^2-abs(s12)^2)*(1-abs(s21)^2-abs(s22)^2))) Complex a = Complex.Abs(Complex.Add(Complex.Multiply(s11[i], Complex.Conjugate(s21[i])), Complex.Multiply(s12[i], Complex.Conjugate(s22[i])))); //A works Complex b = Complex.Subtract(Complex.Subtract(1, Complex.Pow(Complex.Abs(s11[i]), 2.00)), Complex.Pow(Complex.Abs(s12[i]), 2.00)); Complex c = Complex.Subtract(Complex.Subtract(1, Complex.Pow(Complex.Abs(s21[i]), 2.00)), Complex.Pow(Complex.Abs(s22[i]), 2.00)); Complex d = Complex.Divide(a, Complex.Sqrt(Complex.Multiply(b, c))); // the simplified code for an reciprocal device works: //abs(s11*conj(s21) + s21*conj(s11)) / (1 - abs(s11)^2 - abs(s21)^2) // Complex a = Complex.Abs(Complex.Add(Complex.Multiply(s11[i], Complex.Conjugate(s21[i])),Complex.Multiply(s21[i], Complex.Conjugate(s11[i])))); // Complex b = Complex.Subtract(Complex.Subtract(1.0, Complex.Pow(Complex.Abs(s11[i]),2.0)), Complex.Pow(Complex.Abs(s21[i]),2.0)); // Complex d = Complex.Divide(a, b); double f = (double)(d.Magnitude); e.Add(f); } dataArray = e.ToArray(); //abs(s11*conj(s21)+s12*conj(s22))/(sqrt((1-abs(s11)^2-abs(s12)^2)*(1-abs(s21)^2-abs(s22)^2))) plotdata(); label15.Text = Convert.ToString(string.Format("{0:0.00}", (dataArray.Max() * 100) - 100)); label16.Text = Convert.ToString(string.Format("{0:0.00}", (100 - (dataArray.Min() * 100)))); }
/// <summary> /// Reduces a complex Hermitian matrix to a real symmetric tridiagonal matrix using unitary similarity transformations. /// </summary> /// <param name="matrixA">Source matrix to reduce</param> /// <param name="d">Output: Arrays for internal storage of real parts of eigenvalues</param> /// <param name="e">Output: Arrays for internal storage of imaginary parts of eigenvalues</param> /// <param name="tau">Output: Arrays that contains further information about the transformations.</param> /// <param name="order">Order of initial matrix</param> /// <remarks>This is derived from the Algol procedures HTRIDI by /// Smith, Boyle, Dongarra, Garbow, Ikebe, Klema, Moler, and Wilkinson, Handbook for /// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding /// Fortran subroutine in EISPACK.</remarks> static void SymmetricTridiagonalize(Complex[,] matrixA, double[] d, double[] e, Complex[] tau, int order) { double hh; tau[order - 1] = Complex.One; for (var i = 0; i < order; i++) { d[i] = matrixA[i, i].Real; } // Householder reduction to tridiagonal form. for (var i = order - 1; i > 0; i--) { // Scale to avoid under/overflow. var scale = 0.0; var h = 0.0; for (var k = 0; k < i; k++) { scale = scale + Math.Abs(matrixA[i, k].Real) + Math.Abs(matrixA[i, k].Imaginary); } if (scale == 0.0) { tau[i - 1] = Complex.One; e[i] = 0.0; } else { for (var k = 0; k < i; k++) { matrixA[i, k] /= scale; h += matrixA[i, k].MagnitudeSquared(); } Complex g = Math.Sqrt(h); e[i] = scale * g.Real; Complex temp; var f = matrixA[i, i - 1]; if (f.Magnitude != 0) { temp = -(matrixA[i, i - 1].Conjugate() * tau[i].Conjugate()) / f.Magnitude; h += f.Magnitude * g.Real; g = 1.0 + (g / f.Magnitude); matrixA[i, i - 1] *= g; } else { temp = -tau[i].Conjugate(); matrixA[i, i - 1] = g; } if ((f.Magnitude == 0) || (i != 1)) { f = Complex.Zero; for (var j = 0; j < i; j++) { var tmp = Complex.Zero; // Form element of A*U. for (var k = 0; k <= j; k++) { tmp += matrixA[j, k] * matrixA[i, k].Conjugate(); } for (var k = j + 1; k <= i - 1; k++) { tmp += matrixA[k, j].Conjugate() * matrixA[i, k].Conjugate(); } // Form element of P tau[j] = tmp / h; f += (tmp / h) * matrixA[i, j]; } hh = f.Real / (h + h); // Form the reduced A. for (var j = 0; j < i; j++) { f = matrixA[i, j].Conjugate(); g = tau[j] - (hh * f); tau[j] = g.Conjugate(); for (var k = 0; k <= j; k++) { matrixA[j, k] -= (f * tau[k]) + (g * matrixA[i, k]); } } } for (var k = 0; k < i; k++) { matrixA[i, k] *= scale; } tau[i - 1] = temp.Conjugate(); } hh = d[i]; d[i] = matrixA[i, i].Real; matrixA[i, i] = new Complex(hh, scale * Math.Sqrt(h)); } hh = d[0]; d[0] = matrixA[0, 0].Real; matrixA[0, 0] = hh; e[0] = 0.0; }
/// <summary>Solves a system of linear equations whose coefficients are in a triangular band matrix, i.e. op(A) * x = b, where op(A) = A, op(A) = A ^t or op(A) = A^h. /// </summary> /// <param name="n">The order of matrix A.</param> /// <param name="k">The number of super-diagonals of A if the matrix A is provided in its upper triangular representation; the number of sub-diagonals otherwise.</param> /// <param name="a">The triangular band matrix with dimension (<paramref name="lda" />, <paramref name="n" />).</param> /// <param name="x">The vector b (input), x (output) with at least 1 + (<paramref name="n" /> - 1) * | <paramref name="incX" /> | elements (input/output).</param> /// <param name="lda">The leading dimension of <paramref name="a" />, must be at least (1 + <paramref name="k" />).</param> /// <param name="triangularMatrixType">A value whether matrix A is in its upper or lower triangular representation.</param> /// <param name="isUnitTriangular">A value indicating whether the matrix A is unit triangular.</param> /// <param name="transpose">A value indicating whether 'op(A)=A', 'op(A)=A^t' or 'op(A)=A^h'.</param> /// <param name="incX">The increment for the elements of <paramref name="x" />.</param> public void ztbsv(int n, int k, Complex[] a, Complex[] x, int lda, BLAS.TriangularMatrixType triangularMatrixType = BLAS.TriangularMatrixType.UpperTriangularMatrix, bool isUnitTriangular = true, BLAS.MatrixTransposeState transpose = BLAS.MatrixTransposeState.NoTranspose, int incX = 1) { if (n == 0) { return; } int kx = 1; if (incX <= 0) { kx = 1 - (n - 1) * incX; } else if (incX != 1) { kx = 1; } if (transpose == BLAS.MatrixTransposeState.NoTranspose) // x := Inv( A ) * x { if (triangularMatrixType == BLAS.TriangularMatrixType.UpperTriangularMatrix) { kx += (n - 1) * incX; int jx = kx; for (int j = n; j >= 1; j--) { kx -= incX; int ix = kx; int ell = k + 1 - j; if (isUnitTriangular == false) { x[jx - 1] /= a[k + (j - 1) * lda]; } Complex temp = x[jx - 1]; for (int i = j - 1; i >= Math.Max(1, j - k); i--) { x[ix - 1] -= temp * a[ell + i - 1 + (j - 1) * lda]; ix -= incX; } jx -= incX; } } else { int jx = kx; for (int j = 1; j <= n; j++) { kx += incX; int ix = kx; int ell = 1 - j; if (isUnitTriangular == false) { x[jx - 1] /= a[(j - 1) * lda]; } Complex temp = x[jx - 1]; for (int i = j + 1; i <= Math.Min(n, j + k); i++) { x[ix - 1] -= temp * a[ell + i - 1 + (j - 1) * lda]; ix += incX; } jx += incX; } } } else if (transpose == BLAS.MatrixTransposeState.Transpose) // x := Inv( A' ) * x { if (triangularMatrixType == BLAS.TriangularMatrixType.UpperTriangularMatrix) { int jx = kx; for (int j = 1; j <= n; j++) { Complex temp = x[jx - 1]; int ix = kx; int ell = k + 1 - j; for (int i = Math.Max(1, j - k); i <= j - 1; i++) { temp -= a[ell + i - 1 + (j - 1) * lda] * x[ix - 1]; ix += incX; } if (isUnitTriangular == false) { temp /= a[k + (j - 1) * lda]; } x[jx - 1] = temp; jx += incX; if (j > k) { kx += incX; } } } else { kx += (n - 1) * incX; int jx = kx; for (int j = n; j >= 1; j--) { Complex temp = x[jx - 1]; int ix = kx; int ell = 1 - j; for (int i = Math.Min(n, j + k); i >= j + 1; i--) { temp -= a[ell + i - 1 + (j - 1) * lda] * x[ix - 1]; ix -= incX; } if (isUnitTriangular == false) { temp /= a[(j - 1) * lda]; } x[jx - 1] = temp; jx -= incX; if (n - j >= k) { kx -= incX; } } } } else // x := Inv( conj(A)' ) * x { if (triangularMatrixType == BLAS.TriangularMatrixType.UpperTriangularMatrix) { int jx = kx; for (int j = 1; j <= n; j++) { Complex temp = x[jx - 1]; int ix = kx; int ell = k + 1 - j; for (int i = Math.Max(1, j - k); i <= j - 1; i++) { temp -= Complex.Conjugate(a[ell + i - 1 + (j - 1) * lda]) * x[ix - 1]; ix += incX; } if (isUnitTriangular == false) { temp /= Complex.Conjugate(a[k + (j - 1) * lda]); } x[jx - 1] = temp; jx += incX; if (j > k) { kx += incX; } } } else { kx += (n - 1) * incX; int jx = kx; for (int j = n; j >= 1; j--) { Complex temp = x[jx - 1]; int ix = kx; int ell = 1 - j; for (int i = Math.Min(n, j + k); i >= j + 1; i--) { temp -= Complex.Conjugate(a[ell + i - 1 + (j - 1) * lda]) * x[ix - 1]; ix -= incX; } if (isUnitTriangular == false) { temp /= Complex.Conjugate(a[(j - 1) * lda]); } x[jx - 1] = temp; jx -= incX; if (n - j >= k) { kx -= incX; } } } } }
/// <summary> /// 拡張メソッド. 自己共役を返す /// </summary> /// <param name="c"></param> /// <returns></returns> public static Complex Conjugate(this Complex c) => Complex.Conjugate(c);
// sample client for testing public static void test() { Complex a = new Complex(5.0, 6.0); Complex b = new Complex(-3.0, 4.0); System.Diagnostics.Debug.WriteLine("a = " + a); System.Diagnostics.Debug.WriteLine("b = " + b); System.Diagnostics.Debug.WriteLine("Re(a) = " + a.Re); System.Diagnostics.Debug.WriteLine("Im(a) = " + a.Im); System.Diagnostics.Debug.WriteLine("b + a = " + b.Plus(a)); System.Diagnostics.Debug.WriteLine("a - b = " + a.Minus(b)); System.Diagnostics.Debug.WriteLine("a * b = " + a.Times(b)); System.Diagnostics.Debug.WriteLine("b * a = " + b.Times(a)); System.Diagnostics.Debug.WriteLine("a / b = " + a.Divides(b)); System.Diagnostics.Debug.WriteLine("(a / b) * b = " + a.Divides(b).Times(b)); System.Diagnostics.Debug.WriteLine("conj(a) = " + a.Conjugate()); System.Diagnostics.Debug.WriteLine("|a| = " + a.Abs()); System.Diagnostics.Debug.WriteLine("tan(a) = " + a.Tan()); }
public static double zgeco(ref Complex[] a, int lda, int n, ref int[] ipvt) //****************************************************************************80 // // Purpose: // // ZGECO factors a complex matrix and estimates its condition. // // Discussion: // // If RCOND is not needed, ZGEFA is slightly faster. // // To solve A*X = B, follow ZGECO by ZGESL. // // To compute inverse(A)*C, follow ZGECO by ZGESL. // // To compute determinant(A), follow ZGECO by ZGEDI. // // To compute inverse(A), follow ZGECO by ZGEDI. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 21 May 2006 // // Author: // // C++ version by John Burkardt // // Reference: // // Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart, // LINPACK User's Guide, // SIAM, (Society for Industrial and Applied Mathematics), // 3600 University City Science Center, // Philadelphia, PA, 19104-2688. // // Parameters: // // Input/output, Complex A[LDA*N], on input, the matrix to be // factored. On output, an upper triangular matrix and the multipliers // used to obtain it. The factorization can be written A = L*U where // L is a product of permutation and unit lower triangular matrices // and U is upper triangular. // // Input, int LDA, the leading dimension of A. // // Input, int N, the order of the matrix. // // Output, int IPVT[N], the pivot indices. // // Output, double SGECO, an estimate of the reciprocal condition of A. // For the system A*X = B, relative perturbations in A and B of size // EPSILON may cause relative perturbations in X of size (EPSILON/RCOND). // If RCOND is so small that the logical expression // 1.0 + RCOND == 1.0 // is true, then A may be singular to working precision. In particular, // RCOND is zero if exact singularity is detected or the estimate // underflows. // // Local Parameters: // // Workspace, Complex Z[N], a work vector whose contents are usually // unimportant. If A is close to a singular matrix, then Z is // an approximate null vector in the sense that // norm ( A * Z ) = RCOND * norm ( A ) * norm ( Z ). // { int i; int j; int k; int l; double rcond; double s; Complex t; Complex[] z = new Complex [n]; // // Compute the 1-norm of A. // double anorm = 0.0; for (j = 0; j < n; j++) { anorm = Math.Max(anorm, BLAS1Z.dzasum(n, a, 1, index: +0 + j * lda)); } // // Factor. // ZGEFA.zgefa(ref a, lda, n, ref ipvt); // // RCOND = 1/(norm(A)*(estimate of norm(inverse(A)))). // // Estimate = norm(Z)/norm(Y) where A*Z = Y and hermitian(A)*Y = E. // // Hermitian(A) is the Complex.Conjugateugate transpose of A. // // The components of E are chosen to cause maximum local // growth in the elements of W where hermitian(U)*W = E. // // The vectors are frequently rescaled to avoid overflow. // // Solve hermitian(U)*W = E. // Complex ek = new(1.0, 0.0); for (i = 0; i < n; i++) { z[i] = new Complex(0.0, 0.0); } for (k = 1; k <= n; k++) { if (typeMethods.zabs1(z[k - 1]) != 0.0) { ek = typeMethods.zsign1(ek, -z[k - 1]); } if (typeMethods.zabs1(a[k - 1 + (k - 1) * lda]) < typeMethods.zabs1(ek - z[k - 1])) { s = typeMethods.zabs1(a[k - 1 + (k - 1) * lda]) / typeMethods.zabs1(ek - z[k - 1]); BLAS1Z.zdscal(n, s, ref z, 1); ek = new Complex(s, 0.0) * ek; } Complex wk = ek - z[k - 1]; Complex wkm = -ek - z[k - 1]; s = typeMethods.zabs1(wk); double sm = typeMethods.zabs1(wkm); if (typeMethods.zabs1(a[k - 1 + (k - 1) * lda]) != 0.0) { wk /= Complex.Conjugate(a[k - 1 + (k - 1) * lda]); wkm /= Complex.Conjugate(a[k - 1 + (k - 1) * lda]); } else { wk = new Complex(1.0, 0.0); wkm = new Complex(1.0, 0.0); } for (j = k + 1; j <= n; j++) { sm += typeMethods.zabs1(z[j - 1] + wkm * Complex.Conjugate(a[k - 1 + (j - 1) * lda])); z[j - 1] += wk * Complex.Conjugate(a[k - 1 + (j - 1) * lda]); s += typeMethods.zabs1(z[j - 1]); } if (s < sm) { t = wkm - wk; wk = wkm; for (j = k + 1; j <= n; j++) { z[j - 1] += t * Complex.Conjugate(a[k - 1 + (j - 1) * lda]); } } z[k - 1] = wk; } s = 1.0 / BLAS1Z.dzasum(n, z, 1); BLAS1Z.zdscal(n, s, ref z, 1); // // Solve hermitian(L) * Y = W. // for (k = n; 1 <= k; k--) { if (k < n) { z[k - 1] += BLAS1Z.zdotc(n - k, a, 1, z, 1, xIndex: +k + (k - 1) * lda, yIndex: +k); } if (1.0 < typeMethods.zabs1(z[k - 1])) { s = 1.0 / typeMethods.zabs1(z[k - 1]); BLAS1Z.zdscal(n, s, ref z, 1); } l = ipvt[k - 1]; t = z[l - 1]; z[l - 1] = z[k - 1]; z[k - 1] = t; } s = 1.0 / BLAS1Z.dzasum(n, z, 1); BLAS1Z.zdscal(n, s, ref z, 1); double ynorm = 1.0; // // Solve L * V = Y. // for (k = 1; k <= n; k++) { l = ipvt[k - 1]; t = z[l - 1]; z[l - 1] = z[k - 1]; z[k - 1] = t; if (k < n) { BLAS1Z.zaxpy(n - k, t, a, 1, ref z, 1, xIndex: +k + (k - 1) * lda, yIndex: +k); } if (!(1.0 < typeMethods.zabs1(z[k - 1]))) { continue; } s = 1.0 / typeMethods.zabs1(z[k - 1]); BLAS1Z.zdscal(n, s, ref z, 1); ynorm = s * ynorm; } s = 1.0 / BLAS1Z.dzasum(n, z, 1); BLAS1Z.zdscal(n, s, ref z, 1); ynorm = s * ynorm; // // Solve U * Z = V. // for (k = n; 1 <= k; k--) { if (typeMethods.zabs1(a[k - 1 + (k - 1) * lda]) < typeMethods.zabs1(z[k - 1])) { s = typeMethods.zabs1(a[k - 1 + (k - 1) * lda]) / typeMethods.zabs1(z[k - 1]); BLAS1Z.zdscal(n, s, ref z, 1); ynorm = s * ynorm; } if (typeMethods.zabs1(a[k - 1 + (k - 1) * lda]) != 0.0) { z[k - 1] /= a[k - 1 + (k - 1) * lda]; } else { z[k - 1] = new Complex(1.0, 0.0); } t = -z[k - 1]; BLAS1Z.zaxpy(k - 1, t, a, 1, ref z, 1, xIndex: +0 + (k - 1) * lda); } // // Make ZNORM = 1. // s = 1.0 / BLAS1Z.dzasum(n, z, 1); BLAS1Z.zdscal(n, s, ref z, 1); ynorm = s * ynorm; if (anorm != 0.0) { rcond = ynorm / anorm; } else { rcond = 0.0; } return(rcond); }