// Get rotation of complex number private static System.Numerics.Complex[] GetComplexRotation(int numberOfBits, Direction direction) { int directionIndex = (direction == Direction.Forward) ? 0 : 1; // check if the array is already calculated if (complexRotation[numberOfBits - 1, directionIndex] == null) { int n = 1 << (numberOfBits - 1); double uR = 1.0; double uI = 0.0; double angle = System.Math.PI / n * (int)direction; double wR = System.Math.Cos(angle); double wI = System.Math.Sin(angle); double t; System.Numerics.Complex[] rotation = new System.Numerics.Complex[n]; for (int i = 0; i < n; i++) { rotation[i] = new System.Numerics.Complex(uR, uI); t = uR * wI + uI * wR; uR = uR * wR - uI * wI; uI = t; } complexRotation[numberOfBits - 1, directionIndex] = rotation; } return(complexRotation[numberOfBits - 1, directionIndex]); }
/// <summary> /// The fourier transform. /// </summary> /// <param name="characteristics"> /// The characteristics. /// </param> /// <returns> /// Spectrum of the signal as <see cref="T:double[][]"/>. /// </returns> public static double[][] CalculateFastFourierTransform(double[][] characteristics) { var powerOfTwo = PowerOfTwoCeiling(characteristics.Length); var result = new double[powerOfTwo][]; for (int j = 0; j < powerOfTwo; j++) { result[j] = new double[characteristics[0].Length]; } // transforming into complex representation // cycle through all characteristics for (int i = 0; i < characteristics[0].Length; i++) { var complex = new Complex[powerOfTwo]; // cycle through all sequence fragments for (int j = 0; j < powerOfTwo; j++) { complex[j] = j < characteristics.Length ? new Complex(characteristics[j][i], 0) : new Complex(0, 0); } Complex[] complexResult = CalculateFastFourierTransform(complex); // converting array to double for (int g = 0; g < powerOfTwo; g++) { result[g][i] = complexResult[g].Real; } } return result; }
/// <summary> /// Applies the filter to a signal. /// </summary> /// protected unsafe override void ProcessFilter(Signal sourceData, Signal destinationData) { SampleFormat format = sourceData.SampleFormat; int samples = sourceData.Samples; if (format == SampleFormat.Format32BitIeeeFloat) { float *src = (float *)sourceData.Data.ToPointer(); float *dst = (float *)destinationData.Data.ToPointer(); for (int i = 0; i < samples; i++, dst++, src++) { *dst = System.Math.Abs(*src); } } else if (format == SampleFormat.Format128BitComplex) { System.Numerics.Complex *src = (System.Numerics.Complex *)sourceData.Data.ToPointer(); System.Numerics.Complex *dst = (System.Numerics.Complex *)destinationData.Data.ToPointer(); for (int i = 0; i < samples; i++, dst++, src++) { *dst = new System.Numerics.Complex((*src).Magnitude, 0); } } }
private static void AreEqualAngle(Num.Complex a, ComplexD b) { AreEqual( new Num.Complex(a.Real % Constant.PiHalf, a.Imaginary), new ComplexD(b.Real % Constant.PiHalf, b.Imag) ); }
/// <summary> /// Calculates spectrum of given signal. /// </summary> /// <param name="x"> /// Array of signal values. array size should be power of 2. /// </param> /// <returns> /// Spectrum of the signal. /// </returns> public static Complex[] CalculateFastFourierTransform(Complex[] x) { Complex[] result; int n = x.Length; if (n == 2) { result = new Complex[2]; result[0] = x[0] + x[1]; result[1] = x[0] - x[1]; } else { var even = new Complex[n / 2]; var odd = new Complex[n / 2]; for (int i = 0; i < n / 2; i++) { even[i] = x[2 * i]; odd[i] = x[(2 * i) + 1]; } even = CalculateFastFourierTransform(even); odd = CalculateFastFourierTransform(odd); result = new Complex[n]; for (int i = 0; i < n / 2; i++) { result[i] = even[i] + (W(i, n) * odd[i]); result[i + (n / 2)] = even[i] - (W(i, n) * odd[i]); } } return result; }
public static Complex[,] GetFilter(double[,] arr) { int xLength = arr.GetLength(0) - 2 * arr.GetLength(0) / 2 == 0 ? arr.GetLength(0) + 1 : arr.GetLength(0); int yLength = arr.GetLength(1) - 2 * arr.GetLength(1) / 2 == 0 ? arr.GetLength(1) + 1 : arr.GetLength(1); int upperBoundX = (int)(xLength / 2); int lowerBoundX = -1 * upperBoundX; int upperBoundY = (int)(yLength / 2); int lowerBoundY = -1 * upperBoundY; Complex[,] filter = new Complex[xLength, yLength]; double x_, y_ = 0; for (int x = lowerBoundX; x < upperBoundX; x++) { for (int y = lowerBoundY; y < upperBoundY; y++) { if (y < 0) { filter[upperBoundX + x, upperBoundY + y] = 0; continue; } x_ = XY_WithLine.GetX_WithLine(upperBoundX + x, upperBoundY + y); y_ = XY_WithLine.GetY_WithLine(upperBoundX + x, upperBoundY + y); filter[upperBoundX + x, upperBoundY + y] = (2 * x_ * y_ + Complex.ImaginaryOne * (x_ * x_ - y_ * y_)) * Gaussian.CalculateGaussian(x_, y_); } } return filter; }
/// <summary> /// Create multichannel complex signal from floating-point matrix. /// </summary> /// /// <param name="array">Source multichannel float array (matrix).</param> /// <param name="sampleRate">Sampling rate for the signal.</param> /// /// <returns>Returns an instance of complex signal.</returns> /// public static ComplexSignal FromArray(float[,] array, int sampleRate) { int samples = array.GetLength(0); int channels = array.GetLength(1); // check signal size if (!BestCS.Math.Tools.IsPowerOf2(samples)) { throw new InvalidSignalPropertiesException("Signals length should be a power of 2."); } System.Numerics.Complex[,] data = new System.Numerics.Complex[samples, channels]; for (int i = 0; i < samples; i++) { for (int j = 0; j < channels; j++) { data[i, j] = new System.Numerics.Complex(array[i, j], 0); } } byte[] buffer = new byte[data.Length * Marshal.SizeOf(typeof(System.Numerics.Complex))]; GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); Marshal.Copy(handle.AddrOfPinnedObject(), buffer, 0, buffer.Length); handle.Free(); return(new ComplexSignal(buffer, channels, samples, sampleRate)); }
/// <summary> /// 2-D Fast Fourier Transform. /// </summary> /// /// <param name="data">The data to transform..</param> /// <param name="direction">The Transformation direction.</param> /// public static void FFT2(System.Numerics.Complex[][] data, FourierTransform.Direction direction) { int n = data.Length; int m = data[0].Length; // process rows for (int i = 0; i < data.Length; i++) { // transform it FFT(data[i], direction); } // process columns var col = new System.Numerics.Complex[n]; for (int j = 0; j < m; j++) { // copy column for (int i = 0; i < col.Length; i++) { col[i] = data[i][j]; } // transform it FFT(col, direction); // copy back for (int i = 0; i < col.Length; i++) { data[i][j] = col[i]; } } }
/// <summary> /// Computes the circular convolution of the given complex /// vectors. All vectors must have the same length. /// </summary> /// public static void Convolve(System.Numerics.Complex[] x, System.Numerics.Complex[] y, System.Numerics.Complex[] result) { FFT(x, FourierTransform.Direction.Forward); FFT(y, FourierTransform.Direction.Forward); for (int i = 0; i < x.Length; i++) { double xreal = x[i].Real; double ximag = x[i].Imaginary; double yreal = y[i].Real; double yimag = y[i].Imaginary; double re = xreal * yreal - ximag * yimag; double im = ximag * yreal + xreal * yimag; x[i] = new System.Numerics.Complex(re, im); } IDFT(x); // Scaling (because this FFT implementation omits it) for (int i = 0; i < x.Length; i++) { result[i] = x[i] / x.Length; } }
public void ForwardInplaceRealSine() { var samples = Generate.PeriodicMap(16, w => new Complex(Math.Sin(w), 0), 16, 1.0, Constants.Pi2); var spectrum = new Complex[samples.Length]; // real-odd transforms to imaginary odd samples.Copy(spectrum); Control.FourierTransformProvider.Forward(spectrum, FourierTransformScaling.BackwardScaling); // all real components must be zero foreach (var c in spectrum) { Assert.AreEqual(0, c.Real, 1e-12, "real"); } // all imaginary components except second and last musth be zero for (var i = 0; i < spectrum.Length; i++) { if (i == 1) { Assert.AreEqual(-8, spectrum[i].Imaginary, 1e-12, "imag second"); } else if (i == spectrum.Length - 1) { Assert.AreEqual(8, spectrum[i].Imaginary, 1e-12, "imag last"); } else { Assert.AreEqual(0, spectrum[i].Imaginary, 1e-12, "imag"); } } }
/// <summary> /// Computes the circular skewness of the given circular angles. /// </summary> /// /// <param name="angles">A double array containing the angles in radians.</param> /// /// <returns>The circular skewness for the given <paramref name="angles"/>.</returns> /// public static double Skewness(double[] angles) { // compute necessary values double theta = Circular.Mean(angles); System.Numerics.Complex m = CentralMoments(angles, 2); double rho2 = m.Magnitude; double mu2 = m.Phase; // compute skewness double b = 0; // Pewsey, Metrika, 2004 for (int i = 0; i < angles.Length; i++) { b += Math.Sin(2 * Distance(angles[i], theta)); } b /= angles.Length; /* * // alternative skewness measure from Fisher * // Statistical Analysis of Circular Data, p. 34 * double b0 = 0; // (formula 2.29) * double omR = Math.Pow(1 - R, 3 / 2.0); * * for (int i = 0; i < angles.Length; i++) * b0 += rho2 * Math.Sin(Distance(mu2, 2 * theta)) / omR; */ return(b); }
/// <summary> /// Computes the inverse discrete Fourier transform (IDFT) of the given complex /// vector, storing the result back into the vector. The vector can have any length. /// This is a wrapper function. This transform does not perform scaling, so the /// inverse is not a true inverse. /// </summary> /// private static void IDFT(System.Numerics.Complex[] data) { int n = data.Length; if (n == 0) { return; } for (int i = 0; i < data.Length; i++) { data[i] = new System.Numerics.Complex(data[i].Imaginary, data[i].Real); } if ((n & (n - 1)) == 0) { // Is power of 2 TransformRadix2(data); } else { // More complicated algorithm for arbitrary sizes TransformBluestein(data); } for (int i = 0; i < data.Length; i++) { double im = data[i].Imaginary; double re = data[i].Real; data[i] = new System.Numerics.Complex(im, re); } }
/// <summary> /// Recursive solution to determine whether complex number belongs to the Mandelbrot set /// </summary> public MandelbrotResult IsMemberRecursive(Complex c, Complex? z = null, int iteration = 0) { if (iteration == MaxIterations) return new MandelbrotResult(iteration, true); if (z.HasValue && z.Value.Magnitude > 2.0) return new MandelbrotResult(iteration, false); var newZ = z.HasValue ? Complex.Pow(z.Value, 2) + c : Complex.Zero; return IsMemberRecursive(c, newZ, iteration + 1); }
public void ComparePowIntWithPow() { Complex z1 = new Complex(1.6859, 0.3902); Complex actual = z1.Pow(10); Complex expected = z1 * z1 * z1 * z1 * z1 * z1 * z1 * z1 * z1 * z1; Assert.IsTrue(expected.ApproximatelyEquals(actual, epsilon)); }
public ObjectDemoData(Int64 iValue) { this.iInt64 = iValue; this.iDouble = iValue; this.iComplex = new Complex((double)iValue, 0); this.iBigInt = iValue; this.iString = iValue.ToString() + ":"; }
public DataItem(SerializationInfo info, StreamingContext streamingContext) { float x = info.GetSingle("coord_X"); float y = info.GetSingle("coord_Y"); coord = new Vector2(x, y); val = (Complex)info.GetValue("field_val", typeof(System.Numerics.Complex)); }
public Mobius( Complex a, Complex b, Complex c, Complex d ) : this() { A = a; B = b; C = c; D = d; }
/// <summary> /// Performs the Fast Hilbert Transform over a double[] array. /// </summary> /// public static void FHT(double[] data, FourierTransform.Direction direction) { int N = data.Length; // Forward operation if (direction == FourierTransform.Direction.Forward) { // Copy the input to a complex array which can be processed // in the complex domain by the FFT System.Numerics.Complex[] cdata = new System.Numerics.Complex[N]; for (int i = 0; i < N; i++) { cdata[i] = new System.Numerics.Complex(data[i], 0.0); } // Perform FFT FourierTransform.FFT(cdata, FourierTransform.Direction.Forward); //double positive frequencies for (int i = 1; i < (N / 2); i++) { cdata[i] *= 2.0; } // zero out negative frequencies // (leaving out the dc component) for (int i = (N / 2) + 1; i < N; i++) { cdata[i] = System.Numerics.Complex.Zero; } // Reverse the FFT FourierTransform.FFT(cdata, FourierTransform.Direction.Backward); // Convert back to our initial double array for (int i = 0; i < N; i++) { data[i] = cdata[i].Imaginary; } } else // Backward operation { // The inverse Hilbert can be calculated by // negating the transform and reapplying the // transformation. // // H^–1{h(t)} = –H{h(t)} FHT(data, FourierTransform.Direction.Forward); for (int i = 0; i < data.Length; i++) { data[i] = -data[i]; } } }
public void Solve() { var pp = new Point(sc.Integer(), sc.Integer()); var qq = new Point(sc.Integer(), sc.Integer()); var n = sc.Integer(); var P = new Point[n + 2]; P[n] = pp; P[n + 1] = qq; var R = new int[n + 2]; for (int i = 0; i < n; i++) { P[i] = new Point(sc.Integer(), sc.Integer()); R[i] = sc.Integer(); } var dist = new double[n + 2]; for (int i = 0; i < n + 2; i++) { dist[i] = 1e18; } dist[n] = 0; var pq = new BinaryHeapPriorityQueue <KeyValuePair <int, double> >((l, r) => l.Value.CompareTo(r.Value)); pq.Enqueue(new KeyValuePair <C, double>(n, 0)); var used = new bool[n + 2]; foreach (var x in P) { Debug.WriteLine(x); } foreach (var x in R) { Debug.WriteLine(x); } while (pq.Count > 0) { var p = pq.Dequeue(); if (used[p.Key]) { continue; } Debug.WriteLine(p); used[p.Key] = true; for (int i = 0; i < n + 2; i++) { //if (used[i]) continue; var cost = get(P[i], P[p.Key], R[i] + R[p.Key]); if (dist[i] > p.Value + cost) { dist[i] = p.Value + cost; pq.Enqueue(new KeyValuePair <C, double>(i, dist[i])); } } } IO.Printer.Out.WriteLine(dist[n + 1]); }
/// <summary> /// Two dimensional Fast Fourier Transform. /// </summary> /// /// <param name="data">Data to transform.</param> /// <param name="direction">Transformation direction.</param> /// /// <remarks><para><note>The method accepts <paramref name="data"/> array of 2<sup>n</sup> size /// only in each dimension, where <b>n</b> may vary in the [1, 14] range. For example, 16x16 array /// is valid, but 15x15 is not.</note></para></remarks> /// /// <exception cref="ArgumentException">Incorrect data length.</exception> /// public static void FFT2(System.Numerics.Complex[,] data, Direction direction) { int k = data.GetLength(0); int n = data.GetLength(1); // check data size if (!Tools.IsPowerOf2(k) || !Tools.IsPowerOf2(n)) { throw new ArgumentException("The matrix rows and columns must be a power of 2."); } if (k < minLength || k > maxLength || n < minLength || n > maxLength) { throw new ArgumentException("Incorrect data length."); } // process rows var row = new System.Numerics.Complex[n]; for (int i = 0; i < k; i++) { // copy row for (int j = 0; j < row.Length; j++) { row[j] = data[i, j]; } // transform it FourierTransform.FFT(row, direction); // copy back for (int j = 0; j < row.Length; j++) { data[i, j] = row[j]; } } // process columns var col = new System.Numerics.Complex[k]; for (int j = 0; j < n; j++) { // copy column for (int i = 0; i < k; i++) { col[i] = data[i, j]; } // transform it FourierTransform.FFT(col, direction); // copy back for (int i = 0; i < k; i++) { data[i, j] = col[i]; } } }
public static PyComplexObject Create(DkmProcess process, Complex value) { var allocator = process.GetDataItem<PyObjectAllocator>(); Debug.Assert(allocator != null); var result = allocator.Allocate<PyComplexObject>(); result.cval.real.Write(value.Real); result.cval.imag.Write(value.Imaginary); return result; }
public static SparseMatrix PorousMatrix(bool Rigid, double d, Complex k, Complex sin_theta, double freq, double porosity, double tortuosity, double YoungsModulus, double PoissonRatio, double Viscous_Characteristic_Length, double flow_resistivity, double FrameDensity, double Thermal_Permeability_0, double AmbientMeanPressure) { double w = Utilities.Numerics.PiX2 * freq; double v = Biot_Porous_Absorbers.v(); double FrameShear = AbsorptionModels.Biot_Porous_Absorbers.Shear_Modulus(YoungsModulus, PoissonRatio); double kb = 2 * FrameShear * (PoissonRatio + 1) / (3 * (1 - 2 * PoissonRatio)); double BulkMod_Frame = AbsorptionModels.Biot_Porous_Absorbers.BulkMod_Solid(YoungsModulus, PoissonRatio); Complex Kf = Biot_Porous_Absorbers.BulkMod_Fluid(w, AmbientMeanPressure, porosity, Thermal_Permeability_0);//AmbientMeanPressure / (1 - (gamma - 1) / (gamma * alpha)); Complex LameL = YoungsModulus * PoissonRatio / ((1 + PoissonRatio) * (1 - 2 * PoissonRatio)); Complex LameMu = YoungsModulus / (2 * (1 + PoissonRatio)); Complex delta21 = w * w * FrameDensity; Complex delta22 = w * w * FrameDensity; Complex delta23 = delta21 / LameMu; delta21 /= (LameL + 2 * LameMu); delta22 /= (LameL + 2 * LameMu); //Taken from Lauriks, et. al., 1990. double rho12 = Biot_Porous_Absorbers.rho12(porosity, tortuosity); double rhoa = Biot_Porous_Absorbers.rhoA(rho12); double Viscous_Permeability = Biot_Porous_Absorbers.Viscous_Permeability(flow_resistivity); Complex Gw = Biot_Porous_Absorbers.G_w(tortuosity, porosity, Viscous_Permeability, Viscous_Characteristic_Length, freq, v); //Complex rho12eff = Biot_Porous_Absorbers.rho12eff(rhoa, porosity, flow_resistivity, Gw, freq); Complex rho22eff = Biot_Porous_Absorbers.rho22eff(rhoa, porosity, flow_resistivity, Gw, freq); Complex rho11eff = Biot_Porous_Absorbers.rho11eff(FrameDensity, rhoa, porosity, flow_resistivity, Gw, freq); Complex P, Q, R; if (!Rigid) { //Universal (Limp) Frame Case: P = ((1 - porosity) * (1 - kb / BulkMod_Frame) * BulkMod_Frame + porosity * BulkMod_Frame * kb / Kf) / (1 - porosity - kb / BulkMod_Frame + porosity * BulkMod_Frame / Kf); Q = (1 - porosity - kb / BulkMod_Frame) * porosity * BulkMod_Frame / (1 - porosity - kb / BulkMod_Frame + porosity * BulkMod_Frame / Kf); R = porosity * porosity * BulkMod_Frame / (1 - porosity - kb / BulkMod_Frame + porosity * BulkMod_Frame / Kf); } else { //Rigid Frame Case: P = 4 * FrameShear / 3 + kb + (porosity * porosity) * Kf / porosity; R = porosity * Kf; Q = Kf * (1 - porosity); } Complex kt = k * sin_theta; Complex k13 = Complex.Sqrt(delta21 - kt * kt); Complex k23 = Complex.Sqrt(delta22 - kt * kt); Complex k33 = Complex.Sqrt(delta23 - kt * kt); Complex Mu1 = Q * delta21 - w * w * rho11eff / (w * w * rho22eff - R * delta21); Complex Mu2 = Q * delta22 - w * w * rho11eff / (w * w * rho22eff - R * delta22); Complex Mu3 = FrameShear * delta23 - w * w * rho11eff / (w * w * rho22eff); SparseMatrix GH = GammaH_P(kt, w, d, FrameShear, P, Q, R, k13, k23, k33, Mu1, Mu2, Mu3); SparseMatrix G0T = Gamma0T_P(kt, w, FrameShear, P, Q, R, k13, k23, k33, Mu1, Mu2, Mu3); return GH * G0T; }
public void TestIfMulIsEqualToComplexOperator() { var z1 = new Complex(1.6859, 0.3902); var z2 = new Complex(3.51896, -0.458); var w1 = z1 * z2; var w2 = ComplexArithmetic.Multiply(z1, z2); Assert.IsTrue(w1.ApproximatelyEquals(w2, Epsilon)); }
public void NodeVariablesSetsCurrent() { var node = new MockedElement(2).Terminals.ConnectAll(); IComponent component = node; var voltage = new System.Numerics.Complex(3.0, 4.0); component.Variables.First().Setter(voltage); Assert.Equal(voltage, node.Voltage); }
private static void TransformBluestein(Complex[] data) { int n = data.Length; int m = HighestOneBit(n * 2 + 1) << 1; // Trignometric tables var cosTable = new double[n]; var sinTable = new double[n]; for (int i = 0; i < cosTable.Length; i++) { int j = (int)((long)i * i % (n * 2)); // This is more accurate than j = i * i cosTable[i] = Math.Cos(Math.PI * j / n); sinTable[i] = Math.Sin(Math.PI * j / n); } // Temporary vectors and preprocessing var areal = new double[m]; var aimag = new double[m]; for (int i = 0; i < data.Length; i++) { double re = data[i].Real; double im = data[i].Imaginary; areal[i] = +re * cosTable[i] + im * sinTable[i]; aimag[i] = -re * sinTable[i] + im * cosTable[i]; } var breal = new double[m]; var bimag = new double[m]; breal[0] = cosTable[0]; bimag[0] = sinTable[0]; for (int i = 1; i < cosTable.Length; i++) { breal[i] = breal[m - i] = cosTable[i]; bimag[i] = bimag[m - i] = sinTable[i]; } // Convolution var creal = new double[m]; var cimag = new double[m]; Convolve(areal, aimag, breal, bimag, creal, cimag); // Postprocessing for (int i = 0; i < data.Length; i++) { double re = +creal[i] * cosTable[i] + cimag[i] * sinTable[i]; double im = -creal[i] * sinTable[i] + cimag[i] * cosTable[i]; data[i] = new System.Numerics.Complex(re, im); } }
private static void ComplexFromDouble() { // <Snippet2> double doubleValue = 1.032e-16; System.Numerics.Complex c1 = doubleValue; Console.WriteLine(c1); // The example displays the following output: // (1.032E-16, 0) // </Snippet2> }
private static void ComplexFromUInt32() { // <Snippet9> uint value = 197461; System.Numerics.Complex c1 = value; Console.WriteLine(c1); // The example displays the following output: // (197461, 0) // </Snippet9> }
private static void ComplexFromSByte() { // <Snippet6> sbyte sbyteValue = -12; System.Numerics.Complex c1 = sbyteValue; Console.WriteLine(c1); // The example displays the following output: // (-12, 0) // </Snippet6> }
private static void ComplexFromInt32() { // <Snippet4> int intValue = 1034217; System.Numerics.Complex c1 = intValue; Console.WriteLine(c1); // The example displays the following output: // (1034217, 0) // </Snippet4> }
public void TestIfPowIntInFasterThanPow() { int iter = 250000; Complex z = new Complex(1.6859, 0.3902); double averageIntTime = BenchmarkUtil.Benchmark( () => { Complex w = ComplexArithmetic.PowInt(z, 10); }, iter); double averageCpTime = BenchmarkUtil.Benchmark( () => { Complex w = Complex.Pow(z, 10); }, iter); Assert.IsTrue(averageIntTime < averageCpTime); }
private static void ComplexFromInt16() { // <Snippet3> short shortValue = 16024; System.Numerics.Complex c1 = shortValue; Console.WriteLine(c1); // The example displays the following output: // (16024, 0) // </Snippet3> }
private static void ComplexFromSingle() { // <Snippet7> float singleValue = 1.032e-08f; System.Numerics.Complex c1 = singleValue; Console.WriteLine(c1); // The example displays the following output: // (1.03199999657022E-08, 0) // </Snippet7> }
private static void ComplexFromUInt16() { // <Snippet8> ushort shortValue = 421; System.Numerics.Complex c1 = shortValue; Console.WriteLine(c1); // The example displays the following output: // (421, 0) // </Snippet8> }
private static void ComplexFromInt64() { // <Snippet5> long longValue = 951034217; System.Numerics.Complex c1 = longValue; Console.WriteLine(c1); // The example displays the following output: // (951034217, 0) // </Snippet5> }
private static void ComplexFromByte() { // <Snippet1> byte byteValue = 122; System.Numerics.Complex c1 = byteValue; Console.WriteLine(c1); // The example displays the following output: // (122, 0) // </Snippet1> }
public void FourierRadix2IsReversible(FourierOptions options) { var samples = Generate.RandomComplex(0x8000, GetUniform(1)); var work = new Complex[samples.Length]; samples.CopyTo(work, 0); Fourier.Radix2Forward(work, options); Assert.IsFalse(work.ListAlmostEqual(samples, 6)); Fourier.Radix2Inverse(work, options); AssertHelpers.AlmostEqual(samples, work, 12); }
/// <summary> /// Converts the complex signal to a complex array. /// </summary> /// public System.Numerics.Complex[,] ToArray() { System.Numerics.Complex[,] array = new System.Numerics.Complex[Length, Channels]; GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned); IntPtr pointer = handle.AddrOfPinnedObject(); Marshal.Copy(RawData, 0, pointer, array.Length * Marshal.SizeOf(typeof(System.Numerics.Complex))); handle.Free(); return(array); }
public MandelbrotResult IsMemberIterative(Complex c) { var iteration = 0; var z = Complex.Zero; while (iteration < MaxIterations && z.Magnitude < 2) { z = z * z + c; iteration++; } var isMember = (iteration == MaxIterations); return new MandelbrotResult(iteration, isMember); }
static public int Compare(Point a, Point b) { if (a.Real != b.Real) { return((a.Real > b.Real) ? 1 : -1); } else if (a.Imaginary != b.Imaginary) { return(a.Imaginary > b.Imaginary ? 1 : -1); } return(0); }
/// <summary> /// Тихоновская регуляризация /// </summary> /// <param name="filter"> ядро искажения (PSF)</param> /// <returns></returns> public static ConvolutionFilter Filtering(ConvolutionFilter filter) { ///в частотной области ///fn(u,v)=((h*(u,v)/|h(u,v)|^2+gamma*|p(u,v)|^2))*g(u,v) ///fn - приближение ///h - kernel ///h* - комплексно-сопряженная форма kernel ///|h|^2 = h(u,v)*h*(u,v) = u^2+v^2*i ///gamma - какой-то параметр (в инверсном фильтре = 0) ///p(u,v) = оператор Лапласа = [{0 1 0} /// {1 -4 1} /// {0 1 0}] ///g - искаженное изображение Complex[,] otf = OpticalTransferFunction.Psf2otf(filter); int height = otf.GetLength(0); //строк int width = otf.GetLength(1); //столбцов Complex gamma = Complex.Zero; // Complex[,] otfZ = new Complex[height, width]; //комплексно сопряженная матрица ядра Complex[,] otf2 = new Complex[height, width]; //матрица = |h|^2 Complex[,] p = {{0, 1, 0,}, //лапласиан {1, -4, 1,}, {0, 1, 0,},}; p = Fourier.Transform(p); for (int u = 0; u < p.GetLength(0); u++) for (int v = 0; v < p.GetLength(1); v++) p[u, v] = OpticalTransferFunction.ModPow(p[u, v]); for (int u = 0; u < height; u++) for (int v = 0; v < width; v++) otfZ[u, v] = Complex.Conjugate(otf[u, v]); for (int u = 0; u < height; u++) for (int v = 0; v < width; v++) otf2[u, v] = OpticalTransferFunction.ModPow(otf[u, v]); for (int u = 0; u < height; u++) for (int v = 0; v < width; v++) p[u, v] = p[u, v] * gamma; for (int u = 0; u < height; u++) for (int v = 0; v < width; v++) otf2[u, v] = otf2[u, v] + p[u, v]; for (int u = 0; u < height; u++) for (int v = 0; v < width; v++) otf[u, v] = otfZ[u, v] / otf2[u, v]; ConvolutionFilter cf = OpticalTransferFunction.Otf2psf(otf); return cf; }
/// <summary> /// Generates the given number of samples. /// </summary> /// public Signal Generate(int samples) { Signal signal = new Signal(Channels, samples, SamplingRate, Format); int ti = interval * Channels; unsafe { if (Format == SampleFormat.Format32BitIeeeFloat) { for (int c = 0; c < Channels; c++) { float *dst = (float *)signal.Data.ToPointer() + c; for (int i = 0; i < samples; i += interval, dst += ti) { *dst = ampMax; if (Pulses > 0 && i / interval >= Pulses) { break; } } } } else if (Format == SampleFormat.Format128BitComplex) { System.Numerics.Complex campMax = new System.Numerics.Complex(ampMax, 0); for (int c = 0; c < Channels; c++) { System.Numerics.Complex *dst = (System.Numerics.Complex *)signal.Data.ToPointer() + c; for (int i = 0; i < samples; i += interval, dst += ti) { *dst = campMax; if (Pulses > 0 && i / interval >= Pulses) { break; } } } } else { throw new UnsupportedSampleFormatException("Sample format is not supported by the filter."); } } return(signal); }
private static void AreEqual(Num.Complex a, ComplexD b) { bool cond = (a.Real.ApproximateEquals(b.Real, Epsilon) && a.Imaginary.ApproximateEquals(b.Imag, Epsilon)) || (a.Real.Equals(b.Real) && a.Imaginary.Equals(b.Imag)); if (!cond) { Debugger.Break(); } Assert.IsTrue(cond, "{0} != {1}", a, b); }
protected override IterateSinglePointResult? CreateSinglePoint( Complex current, Complex parameter, int maxIterations, double maxMagnitude) { return this.IterateSinglePoint( initial: current, offset: parameter, returnValue: current, maxIterations: maxIterations, maxMagnitude: maxMagnitude); }
Color Mandelbrot(float x, float y) { Numerics.Complex c = new Numerics.Complex(x, y); Numerics.Complex z = c; for (int iter = 0; iter < maxIter; iter++) { z = z * z + c; if (z.Magnitude > 2) { return(Colorize(iter)); } } return(Colorize(maxIter)); }
/// <summary> /// Initializes a new instance of the <see cref="UserCholesky"/> class. This object will compute the /// Cholesky factorization when the constructor is called and cache it's factorization. /// </summary> /// <param name="matrix">The matrix to factor.</param> /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not positive definite.</exception> public UserCholesky(Matrix<Complex> matrix) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare); } // Create a new matrix for the Cholesky factor, then perform factorization (while overwriting). CholeskyFactor = matrix.Clone(); var tmpColumn = new Complex[CholeskyFactor.RowCount]; // Main loop - along the diagonal for (var ij = 0; ij < CholeskyFactor.RowCount; ij++) { // "Pivot" element var tmpVal = CholeskyFactor.At(ij, ij); if (tmpVal.Real > 0.0) { tmpVal = tmpVal.SquareRoot(); CholeskyFactor.At(ij, ij, tmpVal); tmpColumn[ij] = tmpVal; // Calculate multipliers and copy to local column // Current column, below the diagonal for (var i = ij + 1; i < CholeskyFactor.RowCount; i++) { CholeskyFactor.At(i, ij, CholeskyFactor.At(i, ij) / tmpVal); tmpColumn[i] = CholeskyFactor.At(i, ij); } // Remaining columns, below the diagonal DoCholeskyStep(CholeskyFactor, CholeskyFactor.RowCount, ij + 1, CholeskyFactor.RowCount, tmpColumn, Control.NumberOfParallelWorkerThreads); } else { throw new ArgumentException(Resources.ArgumentMatrixPositiveDefinite); } for (var i = ij + 1; i < CholeskyFactor.RowCount; i++) { CholeskyFactor.At(ij, i, Complex.Zero); } } }
public Result FFT(double[] iWave, int iSampleRate = 1000) { if (iWave.Length < iSampleRate) { return(new Result(0)); } // ------------------------------------ // 複數的實部是 訊號源 // ------------------------------------ Complex[] samples = new System.Numerics.Complex[iWave.Length]; for (int i = 0; i < samples.Length; i++) { samples[i] = new System.Numerics.Complex(iWave[i], 0.0); } // ------------------------------------ // 計算結果會覆寫回 samples // ------------------------------------ // FFT MathNet.Numerics.IntegralTransforms.Fourier.Forward(samples, FourierOptions.NoScaling); //MathNet.Numerics.IntegralTransforms.Fourier.Forward(samples, FourierOptions.Matlab); // ------------------------------------ // 計算sample在頻域時離散的間隔是多少hz // ------------------------------------ double number_sample = iWave.Length; double hz_per_sample = (double)iSampleRate / number_sample; // ------------------------------------ // 初始化要回傳的FFT資料結構 // ------------------------------------ // Result r_value = new Result((int)number_sample); // 取樣定理描述 可以忽略高於採樣頻率一半的頻率成分 因有混疊發生 double number_sample2 = number_sample / 2.0; Result r_value = new Result((int)number_sample2); r_value.hz_per_sample = hz_per_sample; // ------------------------------------ for (int i = 0; i < r_value.x_hz.Length; i++) { r_value.x_hz[i] = hz_per_sample * i; // http://www.csie.ntnu.edu.tw/~u91029/Wave.html // Complex Number -> magnitude //r_value.y_magnitude[i] = samples[i].Magnitude; // 將強度正規化 Normalization: magnitude / (number_sample / 2.0) r_value.y_magnitude[i] = samples[i].Magnitude / number_sample2; } // ------------------------------------ r_value.y_magnitude[0] = 0.0; return(r_value); }
public void FourierBluesteinIsReversible(FourierOptions options) { var dft = new DiscreteFourierTransform(); var samples = Generate.RandomComplex(0x7FFF, GetUniform(1)); var work = new Complex[samples.Length]; samples.CopyTo(work, 0); dft.BluesteinForward(work, options); Assert.IsFalse(work.ListAlmostEqual(samples, 6)); dft.BluesteinInverse(work, options); AssertHelpers.ListAlmostEqual(samples, work, 10); }
public void FourierDefaultTransformSatisfiesParsevalsTheorem(int count) { var samples = Sample.Random((u, v) => new Complex(u, v), _uniform, count); var timeSpaceEnergy = (from s in samples select s.MagnitudeSquared()).Mean(); var work = new Complex[samples.Length]; samples.CopyTo(work, 0); // Default -> Symmetric Scaling Transform.FourierForward(work); var frequencySpaceEnergy = (from s in work select s.MagnitudeSquared()).Mean(); Assert.AreApproximatelyEqual(timeSpaceEnergy, frequencySpaceEnergy, 1e-12); }
public void FourierDefaultTransformSatisfiesParsevalsTheorem(int count) { var samples = Generate.RandomComplex(count, GetUniform(1)); var timeSpaceEnergy = (from s in samples select s.MagnitudeSquared()).Mean(); var work = new Complex[samples.Length]; samples.CopyTo(work, 0); // Default -> Symmetric Scaling Fourier.Forward(work); var frequencySpaceEnergy = (from s in work select s.MagnitudeSquared()).Mean(); Assert.AreEqual(timeSpaceEnergy, frequencySpaceEnergy, 1e-12); }
public static Vector<Complex> GenerateRandomDenseVector(int order) { // Fill a matrix with standard random numbers. var normal = new Distributions.Normal { RandomSource = new Random.MersenneTwister(1) }; var v = new DenseVector(order); for (var i = 0; i < order; i++) { v[i] = new Complex(normal.Sample(), normal.Sample()); } // Generate a matrix which is positive definite. return v; }
public static Complex[,] ComplexConvolve(Complex[,] data, Complex[,] kernel ) { var dataReal = data.Select2D(x=>x.Real); var dataImaginary = data.Select2D(x => x.Imaginary); var kernelReal = kernel.Select2D(x => x.Real); var kernelImaginary = kernel.Select2D(x => x.Imaginary); var resultRealPart1 = Convolve(dataReal, kernelReal); var resultRealPart2 = Convolve(dataImaginary, kernelImaginary); var resultImaginaryPart1 = Convolve(dataReal, kernelImaginary); var resultImaginaryPart2 = Convolve(dataImaginary, kernelReal); return KernelHelper.MakeComplexFromDouble( KernelHelper.Subtract(resultRealPart1, resultRealPart2), KernelHelper.Add(resultImaginaryPart1, resultImaginaryPart2)); }
protected IterateSinglePointResult? IterateSinglePoint( Complex initial, Complex offset, Complex returnValue, int maxIterations, double maxMagnitude) { var z1 = initial; for (int i = 0; i < maxIterations; i++) { z1 = z1 * z1 + offset; if (z1.Magnitude > maxMagnitude) { return new IterateSinglePointResult { C = returnValue, Iterations = i }; } } return null; }
public Complex[] GetComplexPlane(Complex lowerLeft, Complex upperRight, int width, int height) { var complexPlane = new Complex[width*height]; var xDistance = upperRight.Real - lowerLeft.Real; var yDistance = upperRight.Imaginary - lowerLeft.Imaginary; var xDistancePerStep = xDistance/width; var yDistancePerStep = yDistance/height; for (var row = 0; row < height; row++) { for (var rowOffset = 0; rowOffset < width; rowOffset++) { var real = lowerLeft.Real + rowOffset*xDistancePerStep; var imaginary = upperRight.Imaginary - row*yDistancePerStep; complexPlane[row*width + rowOffset] = new Complex(real, imaginary); } } return complexPlane; }
public void FourierDefaultTransformIsReversible() { var samples = Generate.RandomComplex(0x7FFF, GetUniform(1)); var work = new Complex[samples.Length]; samples.CopyTo(work, 0); Transform.FourierForward(work); Assert.IsFalse(work.ListAlmostEqual(samples, 6)); Transform.FourierInverse(work); AssertHelpers.ListAlmostEqual(samples, work, 10); Transform.FourierInverse(work, FourierOptions.Default); Assert.IsFalse(work.ListAlmostEqual(samples, 6)); Transform.FourierForward(work, FourierOptions.Default); AssertHelpers.ListAlmostEqual(samples, work, 10); }
/// <summary> /// Draws the DFT. /// </summary> /// <param name="funcValues">The function values.</param> /// <param name="zedGraphControl_abs">The zed graph control_abs.</param> /// <param name="zedGraphControl_phase">The zed graph control_phase.</param> /// <param name="zedGraphControl_revers">The zed graph control_revers.</param> private void DrawDFT(Complex[] funcValues, ZedGraphControl zedGraphControl_abs, ZedGraphControl zedGraphControl_phase, ZedGraphControl zedGraphControl_revers) { GraphPane pane_abs = zedGraphControl_abs.GraphPane; GraphPane pane_phase = zedGraphControl_phase.GraphPane; GraphPane pane_revers = zedGraphControl_revers.GraphPane; pane_abs.Title.Text = "Амплитудный спектр"; pane_phase.Title.Text = "Фазовый спектр"; pane_revers.Title.Text = "Обратное преобразование"; pane_abs.CurveList.Clear(); pane_phase.CurveList.Clear(); pane_revers.CurveList.Clear(); PointPairList list_abs = new PointPairList(); PointPairList list_phase = new PointPairList(); PointPairList list_revers = new PointPairList(); Complex[] values = FourierTransformUtils.MakeDFT(funcValues, TransformDirection.Direct); Complex[] reverseValues = FourierTransformUtils.MakeDFT(values, TransformDirection.Reverse); for (int i = 0; i < values.Length; i++) { list_abs.Add(i, values[i].Magnitude); list_phase.Add(i, values[i].Phase); list_revers.Add(i, reverseValues[i].Real); } LineItem curve_abs = pane_abs.AddCurve("", list_abs, Color.Blue, SymbolType.None); LineItem curve_phase = pane_phase.AddCurve("", list_phase, Color.Blue, SymbolType.None); LineItem curve_revers = pane_revers.AddCurve("", list_revers, Color.Blue, SymbolType.None); zedGraphControl_abs.AxisChange(); zedGraphControl_phase.AxisChange(); zedGraphControl_revers.AxisChange(); zedGraphControl_abs.Invalidate(); zedGraphControl_phase.Invalidate(); zedGraphControl_revers.Invalidate(); }
public static Matrix<Complex> GenerateRandomDenseMatrix(int row, int col) { // Fill a matrix with standard random numbers. var normal = new Distributions.Normal { RandomSource = new Random.MersenneTwister(1) }; var matrixA = new DenseMatrix(row, col); for (var i = 0; i < row; i++) { for (var j = 0; j < col; j++) { matrixA[i, j] = new Complex(normal.Sample(), normal.Sample()); } } // Generate a matrix which is positive definite. return matrixA; }
public void CanComputePower() { var a = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); var b = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqual( new Complex(9.99998047207974718744e-1, -1.76553541154378695012e-6), a.Power(b), 15); a = new Complex(0.0, 1.19209289550780998537e-7); b = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqual(new Complex(1.00000018725172576491, 1.90048076369011843105e-6), a.Power(b), 15); a = new Complex(0.0, -1.19209289550780998537e-7); b = new Complex(0.0, 0.5); AssertHelpers.AlmostEqual(new Complex(-2.56488189382693049636e-1, -2.17823120666116144959), a.Power(b), 15); a = new Complex(0.0, 0.5); b = new Complex(0.0, -0.5); AssertHelpers.AlmostEqual(new Complex(2.06287223508090495171, 7.45007062179724087859e-1), a.Power(b), 15); a = new Complex(0.0, -0.5); b = new Complex(0.0, 1.0); AssertHelpers.AlmostEqual(new Complex(3.70040633557002510874, -3.07370876701949232239), a.Power(b), 15); a = new Complex(0.0, 2.0); b = new Complex(0.0, -2.0); AssertHelpers.AlmostEqual(new Complex(4.24532146387429353891, -2.27479427903521192648e1), a.Power(b), 15); a = new Complex(0.0, -8.388608e6); b = new Complex(1.19209289550780998537e-7, 0.0); AssertHelpers.AlmostEqual(new Complex(1.00000190048219620166, -1.87253870018168043834e-7), a.Power(b), 15); a = new Complex(0.0, 0.0); b = new Complex(0.0, 0.0); AssertHelpers.AlmostEqual(new Complex(1.0, 0.0), a.Power(b), 15); a = new Complex(0.0, 0.0); b = new Complex(1.0, 0.0); AssertHelpers.AlmostEqual(new Complex(0.0, 0.0), a.Power(b), 15); a = new Complex(0.0, 0.0); b = new Complex(-1.0, 0.0); AssertHelpers.AlmostEqual(new Complex(double.PositiveInfinity, 0.0), a.Power(b), 15); a = new Complex(0.0, 0.0); b = new Complex(-1.0, 1.0); AssertHelpers.AlmostEqual(new Complex(double.PositiveInfinity, double.PositiveInfinity), a.Power(b), 15); a = new Complex(0.0, 0.0); b = new Complex(0.0, 1.0); Assert.That(a.Power(b).IsNaN()); }
private ImageSource DrawMandelbrot(Rect area) { var pixelHeight = (int)MandelbrotImage.Height; var pixelWidth = (int)MandelbrotImage.Width; var bitmap = new WriteableBitmap(pixelWidth, pixelHeight, 96, 96, PixelFormats.Bgra32, null); var bytesPerPixel = bitmap.Format.BitsPerPixel / 8; var pixels = new byte[pixelHeight * pixelWidth * bytesPerPixel]; var stride = pixelWidth * bytesPerPixel; var xScale = (area.Right - area.Left) / pixelWidth; var yScale = (area.Top - area.Bottom) / pixelHeight; var mandelbrotSolver = new MandelbrotSolver(maxIterations: 50); var pixelIndices = Enumerable.Range(0, pixels.Length).Where(i => i % 4 == 0); Parallel.ForEach(pixelIndices, i => { var yPixel = i / stride; var xPixel = i % stride / bytesPerPixel; var xCoord = area.Left + xPixel * xScale; var yCoord = area.Top - yPixel * yScale; var c = new Complex(xCoord, yCoord); var mandelbrotResult = mandelbrotSolver.IsMemberIterative(c); var colour = IterationColour(mandelbrotResult.Iterations); pixels[i] = colour.B; pixels[i + 1] = colour.G; pixels[i + 2] = colour.R; pixels[i + 3] = colour.A; }); var sourceRect = new Int32Rect(0, 0, pixelWidth, pixelHeight); bitmap.WritePixels(sourceRect, pixels, stride, 0); return bitmap; }
public void TestSqrt() { var z = new Complex(1.961570561, 0.3901806440); var w = ComplexArithmetic.Sqrt(z); Assert.IsTrue(z.ApproximatelyEquals(w * w, Epsilon)); z = new Complex(-1.961570561, 0.3901806440); w = ComplexArithmetic.Sqrt(z); Assert.IsTrue(z.ApproximatelyEquals(w * w, Epsilon)); z = new Complex(-1.961570561, -0.3901806440); w = ComplexArithmetic.Sqrt(z); Assert.IsTrue(z.ApproximatelyEquals(w * w, Epsilon)); z = new Complex(1.961570561, -0.3901806440); w = ComplexArithmetic.Sqrt(z); Assert.IsTrue(z.ApproximatelyEquals(w * w, Epsilon)); }
public void TestRootsOf() { Complex[] rootsOf4 = { 2.0, -2.0 }; Complex[] rootsOfMinus4 = { 2.0 * Complex.ImaginaryOne, -2.0 * Complex.ImaginaryOne }; Complex z = Complex.FromPolarCoordinates(16.0, MathematicalConstants.PIOverFour); Complex[] rootsOfz = { new Complex(1.961570561,0.3901806440), new Complex(-0.3901806440,1.961570561), new Complex (-1.961570561,0.3901806440), new Complex(-0.3901806440,-1.961570561) }; Complex[] aRootsOf4 = new Complex(4.0,0).Roots(2); Complex[] aRootsOfMinus4 = new Complex(-4.0, 0).Roots(2); Complex[] aRootsOfz = z.Roots(4); Assert.AreEqual(rootsOf4.Length, aRootsOf4.Length); for (int i = 0; i < rootsOf4.Length; i++) { bool assert = rootsOf4[i].ApproximatelyEquals(aRootsOf4[i], epsilon); Assert.IsTrue(assert); } Assert.AreEqual(rootsOfMinus4.Length, aRootsOfMinus4.Length); for (int i = 0; i < rootsOfMinus4.Length; i++) { Assert.IsTrue(rootsOfMinus4[i].ApproximatelyEquals(aRootsOfMinus4[i], epsilon)); } Assert.AreEqual(rootsOfz.Length, aRootsOfz.Length); for (int i = 0; i < rootsOfz.Length; i++) { Assert.IsTrue(rootsOfz[i].ApproximatelyEquals(aRootsOfz[i], epsilon)); } }