//b == Exp(a) //c == 1/Exp(a) public static void Exp(Complex a, out Complex b, out Complex c) { double d = Math.Exp(a.Real); Complex e = new Complex(Math.Cos(a.Imaginary), Math.Sin(a.Imaginary)); b = e * d; c = b.Reciprocal(); }

public static Complex Tanh(Complex z) { double x = Math.Tanh(z.Re); double y = Math.Tan(z.Im); return new Complex(x, y) / new Complex(1, x * y); }

public override void addOpperand(Calc calc,Complex c) { //calc.Opperand1=calc.Total; //calc.Opperand2=c; calc.Total=c; calc.CurrentState=OpperandEnteredState.Singleton; }

public JuliaWithClouds(ulong IterCount, double LeftEdge, double RightEdge, double TopEdge, double BottomEdge, Complex ComplexConst,int MaxAmmountAtTrace=100,int AbcissStepSize=20,int OrdinateStepSize=20) : base(IterCount,LeftEdge,RightEdge,TopEdge,BottomEdge,ComplexConst) { _max_ammount_at_trace = MaxAmmountAtTrace; _abciss_step_length = AbcissStepSize; _ordinate_step_length = OrdinateStepSize; }

public Hash(Complex[][] comData) { this.comData = comData; width = comData.Length; if (width != 0) height = 600; }

public static void Start(Random rnd) { int length = 4096; var masComplex1 = new Complex[length]; var masSimdComplex1 = new Vector2[length]; var masComplex2 = new Complex[length]; var masSimdComplex2 = new Vector2[length]; for (int i = 0; i < length; i++) { float v1 = (float) rnd.NextDouble()*1000; float v2 = (float) rnd.NextDouble()*1000; masComplex1[i] = new Complex(v1, v2); masSimdComplex1[i] = new Vector2(v1,v2); v1 = (float)rnd.NextDouble() * 1000; v2 = (float)rnd.NextDouble() * 1000; masComplex2[i] = new Complex(v1, v2); masSimdComplex2[i] = new Vector2(v1, v2); } Extensions.TestTime(() => TestWithoutSimd(masComplex1, masComplex2), "Время для complex "); Extensions.TestTime(() => TestWithSimd(masSimdComplex1, masSimdComplex2), "Время для complex(simd) "); }

private static void VerifyFactoryMethod(double magnitude, double phase) { double m = magnitude; double p = phase; Complex c_new = Complex.FromPolarCoordinates(magnitude, phase); //Double.IsNaN(magnitude) is checked in the verifiation method. if (Double.IsNaN(phase) || Double.IsInfinity(phase)) { magnitude = Double.NaN; phase = Double.NaN; } // Special check in Complex.Abs method else if (Double.IsInfinity(magnitude)) { magnitude = Double.PositiveInfinity; phase = Double.NaN; } if (false == Support.VerifyMagnitudePhaseProperties(c_new, magnitude, phase)) { Console.WriteLine("Error_89fdl!!! FromPolorCoordinates: ({0}, {1})", m, p); Assert.True(false, "Verification Failed"); } else // if the first verification returns TrUe, do the second one! { Complex c_new_ctor = new Complex(c_new.Real, c_new.Imaginary); if (false == Support.VerifyMagnitudePhaseProperties(c_new_ctor, magnitude, phase)) { Console.WriteLine("Error_fs46!!! FromPolorCoordinates: ({0}, {1})", m, p); Assert.True(false, "Verification Failed"); } } }

//--------------------------------------------------------------------------------------------- /// <summary> /// Clamp length (modulus) of the elements in the complex array /// </summary> /// <param name = "array"></param> /// <param name = "fMinimum"></param> /// <param name = "fMaximum"></param> public static void ClampLength(Complex[] array, double fMinimum, double fMaximum) { for (int i = 0; i < array.Length; i++) { array[i] = Complex.FromModulusArgument(Math.Max(fMinimum, Math.Min(fMaximum, array[i].GetModulus())), array[i].GetArgument()); } }

/// <summary> /// Initializes a new instance of the <see cref="UserQR"/> class. This object will compute the /// QR factorization when the constructor is called and cache it's factorization. /// </summary> /// <param name="matrix">The matrix to factor.</param> /// <param name="method">The QR factorization method to use.</param> /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception> public static UserQR Create(Matrix<Complex> matrix, QRMethod method = QRMethod.Full) { if (matrix.RowCount < matrix.ColumnCount) { throw Matrix.DimensionsDontMatch<ArgumentException>(matrix); } Matrix<Complex> q; Matrix<Complex> r; var minmn = Math.Min(matrix.RowCount, matrix.ColumnCount); var u = new Complex[minmn][]; if (method == QRMethod.Full) { r = matrix.Clone(); q = Matrix<Complex>.Build.SameAs(matrix, matrix.RowCount, matrix.RowCount); for (var i = 0; i < matrix.RowCount; i++) { q.At(i, i, 1.0f); } for (var i = 0; i < minmn; i++) { u[i] = GenerateColumn(r, i, i); ComputeQR(u[i], r, i, matrix.RowCount, i + 1, matrix.ColumnCount, Control.MaxDegreeOfParallelism); } for (var i = minmn - 1; i >= 0; i--) { ComputeQR(u[i], q, i, matrix.RowCount, i, matrix.RowCount, Control.MaxDegreeOfParallelism); } } else { q = matrix.Clone(); for (var i = 0; i < minmn; i++) { u[i] = GenerateColumn(q, i, i); ComputeQR(u[i], q, i, matrix.RowCount, i + 1, matrix.ColumnCount, Control.MaxDegreeOfParallelism); } r = q.SubMatrix(0, matrix.ColumnCount, 0, matrix.ColumnCount); q.Clear(); for (var i = 0; i < matrix.ColumnCount; i++) { q.At(i, i, 1.0f); } for (var i = minmn - 1; i >= 0; i--) { ComputeQR(u[i], q, i, matrix.RowCount, i, matrix.ColumnCount, Control.MaxDegreeOfParallelism); } } return new UserQR(q, r, method); }

public static Complex operator +(Complex c1, Complex c2) { int cnt = c1.b * c2.b; int sum = c2.b * c1.a + c1.b * c2.a; if (cnt > sum) { for (int i = sum; i > 2; i--) { if (cnt % i == 0 && sum % i == 0) { cnt = cnt / i; sum = sum / i; break; } } } else { for (int i = cnt; i > 2; i--) { if (cnt % i == 0 && sum % i == 0) { cnt = cnt / i; sum = sum / i; break; } } } Complex c3 = new Complex(sum, cnt); return c3; }

static void Main(string[] args) { Complex c1 = new Complex(1, 2); Complex c2 = new Complex(1, 2); Complex c3 = new Complex(); Console.WriteLine(c1); Console.WriteLine(c2); Console.WriteLine(c3); Complex c4 = c1.Add(c2); Console.WriteLine(c4); Complex c5 = c2.Subtract(c1); Console.WriteLine(c5); Complex c6 = c1.Multiply(c2); Console.WriteLine(c6); if(c1.Equals(c2)) Console.WriteLine("c1 este egal cu c2"); else Console.WriteLine("c1 nu este egal cu c2"); }

public void SetVar(string varname, Complex value) { var root = Root; if (root.m_variables == null) root.m_variables = new Dictionary<string, Complex>(); root.m_variables[varname.ToLower()] = value; }

public void ExecuteWithParamsTest() { var complex = new Complex(5, 2); var exp = new ComplexNumber(complex); Assert.Equal(complex, exp.Execute(null)); }

public void ExecuteTest() { var complex = new Complex(5, 2); var exp = new ComplexNumber(complex); Assert.Equal(complex, exp.Execute()); }

public void processData(ref Complex[][] res, ref int resLen) { resLen = 0; int channels = 2; int pbs = 4096*2*channels; for(int i = 0; i<len/pbs; i++) { comData = new Complex[10000]; comLen = 0; for (int j = i*pbs, cur = 0; j < (i+1)*pbs; j+=2*channels, cur++) { float sum = 0; for (int k = 0; k < channels; k++) sum += (buf[j + 2 * k + 1] << 8) | (buf[j + 2 * k]); sum /= channels; comData[comLen].X = sum; comData[comLen].X *= (float)FastFourierTransform.HammingWindow(cur, 4096); comData[comLen].Y = 0; comLen++; } FastFourierTransform.FFT(true, 12, comData); res[resLen] = comData; resLen++; } resLen++; resLen--; }

/// <summary> /// Gets the correlation. /// </summary> /// <param name="originalVector">The original vector.</param> /// <param name="correlationVector">The correlation vector.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Different length of vectors</exception> public static Complex[] GetCorrelation(Complex[] originalVector, Complex[] correlationVector) { if (originalVector.Length != correlationVector.Length) { throw new ArgumentException("Different length of vectors"); } CorrelationComplexibility = 0; // ReSharper disable once InconsistentNaming var N = originalVector.Length; var result = new Complex[N]; for (var i = 0; i < N; i++) { for (var j = 0; j < N; j++) { if (i + j < N) { result[i] += originalVector[j] * correlationVector[i + j]; CorrelationComplexibility++; } else { result[i] += originalVector[j] * correlationVector[i + j - N]; CorrelationComplexibility++; } } result[i] /= N; } return result; }

}//multiply public cFloat divide(cFloat c1, cFloat c2){ Complex comp1 = new Complex(c1.getReal(), c1.getImg()); Complex comp2 = new Complex(c2.getReal(), c1.getImg()); Complex comp3 = comp1 / comp2; return new cFloat((float)comp3.Real, (float)comp3.Imaginary); }//divide

private static void VerifyBinaryMultiplyResult(Double realFirst, Double imgFirst, Double realSecond, Double imgSecond) { // calculate the expected results Double realExpectedResult = realFirst * realSecond - imgFirst * imgSecond; Double imaginaryExpectedResult = realFirst * imgSecond + imgFirst * realSecond; // Create complex numbers Complex cFirst = new Complex(realFirst, imgFirst); Complex cSecond = new Complex(realSecond, imgSecond); // arithmetic multiply (binary) operation Complex cResult = cFirst * cSecond; // verify the result if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imaginaryExpectedResult)) { Console.WriteLine("ErRoR! Binary Multiply Error!"); Console.WriteLine("Binary Multiply test = ({0}, {1}) * ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond); Assert.True(false, "Verification Failed"); } // arithmetic multiply (static) operation cResult = Complex.Multiply(cFirst, cSecond); // verify the result if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imaginaryExpectedResult)) { Console.WriteLine("ErRoR! Multiply (Static) Error!"); Console.WriteLine("Multiply (Static) test = ({0}, {1}) * ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond); Assert.True(false, "Verification Failed"); } }

/// <summary> /// Clamp elements in the complex array to range [minimum,maximum] /// </summary> /// <param name="array"></param> /// <param name="minimum"></param> /// <param name="maximum"></param> public static void Clamp( Complex[] array, Complex minimum, Complex maximum ) { for( int i = 0; i < array.Length; i ++ ) { array[i].Re = Math.Min( Math.Max( array[ i ].Re, minimum.Re ), maximum.Re ); array[i].Im = Math.Min( Math.Max( array[ i ].Re, minimum.Im ), maximum.Im ); } }

private static void VerifySqrtWithRectangularForm(Double real, Double imaginary) { // sqrt(a+bi) = +- (sqrt(r + a) + i sqrt(r - a) sign(b)) sqrt(2) / 2, unless a=-r and y = 0 Complex complex = new Complex(real, imaginary); Double expectedReal = 0.0; Double expectedImaginary = 0.0; if (0 == imaginary) { if (real == -complex.Magnitude) expectedImaginary = Math.Sqrt(-real); else expectedReal = Math.Sqrt(real); } else { Double scale = 1 / Math.Sqrt(2); expectedReal = scale * Math.Sqrt(complex.Magnitude + complex.Real); expectedImaginary = scale * Math.Sqrt(complex.Magnitude - complex.Real); if (complex.Imaginary < 0) { expectedImaginary = -expectedImaginary; } } VerifySqrtWithRectangularForm(real, imaginary, expectedReal, expectedImaginary); }

public static void RunTests_BoundaryValues() { // Verify test results with Max Complex max = new Complex(double.MaxValue, double.MaxValue); Complex complexExp = Complex.Exp(max); Support.VerifyRealImaginaryProperties(complexExp, Math.Cos(double.MaxValue) * double.PositiveInfinity, double.PositiveInfinity, string.Format("Exp(Max) is not (Infinity, Infinity)")); // Verify test results with MaxReal Complex maxReal = new Complex(double.MaxValue, 0.0); complexExp = Complex.Exp(max); Support.VerifyRealImaginaryProperties(complexExp, Math.Cos(double.MaxValue) * double.PositiveInfinity, double.PositiveInfinity, string.Format("Exp(MaxReal) is not (Infinity, Infinity))")); // Verify test results with MaxImg VerifyExpWithAddition(0.0, double.MaxValue); // Verify test results with Min VerifyExpWithAddition(double.MinValue, double.MinValue); // Verify test results with MinReal VerifyExpWithAddition(double.MinValue, 0.0); // Verify test results with MinImaginary VerifyExpWithAddition(0.0, double.MinValue); }

public void ExecuteTest1() { var complex = new Complex(3.1, 2.5); var exp = new Reciprocal(new ComplexNumber(complex)); Assert.Equal(Complex.Reciprocal(complex), exp.Execute()); }

public Complex response(double freq) { int i; Complex rnum = 0; Complex rden = 0; Complex[] omega = new Complex[s.Length]; Complex z = Complex.Exp(new Complex(0, 2 * Math.PI * freq)); omega[0] = 1.0; omega[1] = z; for (i = 2; i < s.Length; i++) omega[i] = omega[i - 1] * z; for (i = 0; i < a.Length; i++) rnum += a[i] * omega[i]; rden = omega[0]; for (i = 1; i < b.Length; i++) rden += b[i] * omega[i]; if (rden.Magnitude == 0) { return Double.MaxValue; } else { return rnum / rden; } }

public void ToStringTest() { var complex = new Complex(3.1, 2.5); var exp = new Reciprocal(new ComplexNumber(complex)); Assert.Equal("reciprocal(3.1+2.5i)", exp.ToString()); }

/// <summary> /// Computes an Fast Fourier Transform. /// </summary> /// <param name="data">Array of complex numbers. This array provides the input data and is used to store the result of the FFT.</param> /// <param name="exponent">The exponent n.</param> /// <param name="mode">The <see cref="FftMode"/> to use. Use <see cref="FftMode.Forward"/> as the default value.</param> public static void Fft(Complex[] data, int exponent, FftMode mode = FftMode.Forward) { //count; if exponent = 12 -> c = 2^12 = 4096 int c = (int)Math.Pow(2, exponent); //binary inversion Inverse(data, c); int j0, j1, j2 = 1; float n0, n1, tr, ti, m; float v0 = -1, v1 = 0; //move to outer scope to optimize performance int j, i; for (int l = 0; l < exponent; l++) { n0 = 1; n1 = 0; j1 = j2; j2 <<= 1; //j2 * 2 for (j = 0; j < j1; j++) { for (i = j; i < c; i += j2) { j0 = i + j1; //-- tr = n0 * data[j0].Real - n1 * data[j0].Imaginary; ti = n0 * data[j0].Imaginary + n1 * data[j0].Real; //-- data[j0].Real = data[i].Real - tr; data[j0].Imaginary = data[i].Imaginary - ti; //add data[i].Real += tr; data[i].Imaginary += ti; } //calc coeff m = v0 * n0 - v1 * n1; n1 = v1 * n0 + v0 * n1; n0 = m; } if (mode == FftMode.Forward) { v1 = (float)Math.Sqrt((1f - v0) / 2f); } else { v1 = (float)-Math.Sqrt((1f - v0) / 2f); } v0 = (float)Math.Sqrt((1f + v0) / 2f); } if (mode == FftMode.Forward) { Forward(data, c); } }

public override void AddVectorToScaledVector(Complex[] y, Complex alpha, Complex[] x, Complex[] result) { if (y == null) { throw new ArgumentNullException("y"); } if (x == null) { throw new ArgumentNullException("x"); } if (y.Length != x.Length) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (!ReferenceEquals(y, result)) { Array.Copy(y, 0, result, 0, y.Length); } if (alpha == Complex.Zero) { return; } SafeNativeMethods.z_axpy(y.Length, alpha, x, result); }

public static Complex[] FFT(float[] samples) { //Debug.Assert((samples.Length & (samples.Length - 1)) == 0); //FIXME: what happens if I pass non power of 2?? #if false Func<int, int, double> window_fn = FastFourierTransform.HammingWindow; #else Func<int, int, double> window_fn = (a, b) => 1; #endif Complex[] fftData = new Complex[samples.Length]; for (int i = 0; i < samples.Length; ++i) { fftData[i].X = (float) (samples[i] * window_fn(i, samples.Length)); fftData[i].Y = 0; } /* in-place, forwards FFT. * Input is a sequence of complex numbers with sample amplitude in the real part and a 0 imaginary part. * Output is a sequence of complex numbers, whose modulus is the amplitude at that frequency. * Outputs range in frequency from 0 to sample rate */ FastFourierTransform.FFT(true, (int) Math.Log(fftData.Length, 2), fftData); return fftData; }

public void Update(Complex[] fftResults) { // no need to repaint too many frames per second if (updateCount++ % 2 == 0) { return; } if (fftResults.Length / 2 != bins) { this.bins = fftResults.Length / 2; CalculateXScale(); } for (int n = 0; n < fftResults.Length / 2; n+= binsPerPoint) { // averaging out bins double yPos = 0; for (int b = 0; b < binsPerPoint; b++) { yPos += GetYPosLog(fftResults[n+b]); } AddResult(n / binsPerPoint, yPos / binsPerPoint); } }

// compute the FFT of x[], assuming its length is a power of 2 public static Complex[] fft(Complex[] x) { int N = x.Length; // base case if (N == 1) return new Complex[] { x[0] }; // radix 2 Cooley-Tukey FFT if (N % 2 != 0) { throw new Exception("N is not a power of 2"); } // fft of even terms Complex[] even = new Complex[N/2]; for (int k = 0; k < N/2; k++) { even[k] = x[2*k]; } Complex[] q = fft(even); // fft of odd terms Complex[] odd = even; // reuse the array for (int k = 0; k < N/2; k++) { odd[k] = x[2*k + 1]; } Complex[] r = fft(odd); // combine Complex[] y = new Complex[N]; for (int k = 0; k < N/2; k++) { double kth = -2 * k * Math.PI / N; Complex wk = new Complex(Math.Cos(kth), Math.Sin(kth)); Complex tmp = wk * r[k]; y[k] = q[k] + tmp; y[k + N/2] = q[k] - tmp; } return y; }

//b == Cosh(a) //c == Sinh(a) public static void CoshSinh(Complex a, out Complex b, out Complex c) { Complex d, e; Exp(a, out d, out e); b = (d + e) / 2; c = (d - e) / 2; }