/// <summary>
        /// Check if a cubic Bezier lies within a given distance of the origin.
        /// "Origin" means *the* origin (0,0), not the start of the curve. Note that no
        /// checks are made on the start and end positions of the curve; this function
        /// only checks the inside of the curve.
        /// </summary>
        /// <param name="p0">p0 (complex): Start point of curve.</param>
        /// <param name="p1">p1 (complex): First handle of curve.</param>
        /// <param name="p2">p2 (complex): Second handle of curve.</param>
        /// <param name="p3">p3 (complex): End point of curve.</param>
        /// <param name="maxError">tolerance (double): Distance from origin.</param>
        /// <returns>True if the cubic Bezier `p` entirely lies within a distance `tolerance` of the origin, false otherwise.</returns>
        private static bool CubicFarthestFitsInside(Complex p0, Complex p1, Complex p2, Complex p3, float maxError)
        {
            // First check p2 then p1, as p2 has higher error early on.
            if (Complex.Abs(p2) <= maxError && Complex.Abs(p1) <= maxError)
            {
                return(true);
            }

            // Split
            var mid = (p0 + 3 * (p1 + p2) + p3) * 0.125;

            if (Complex.Abs(mid) > maxError)
            {
                return(false);
            }

            var deriv3 = (p3 + p2 - p1 - p0) * 0.125;

            return(CubicFarthestFitsInside(p0, (p0 + p1) * 0.5, mid - deriv3, mid, maxError) &&
                   CubicFarthestFitsInside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, maxError));
        }
Example #2
0
        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();
        }
Example #3
0
        private static void VerifyBinaryAbs(Double real, Double imaginary, Double expected)
        {
            // Create complex numbers
            Complex cComplex = new Complex(real, imaginary);
            Double  abs      = Complex.Abs(cComplex);

            if (!(abs.Equals((Double)expected) || Support.IsDiffTolerable(abs, expected)))
            {
                Console.WriteLine("Error_asd872!!! Abs ({0}, {1}) Actual: {2}, Expected: {3}", real, imaginary, abs, expected);
                Assert.True(false, "Verification Failed");
            }
            else // do the second verification
            {
                Double absNegative = Complex.Abs(-cComplex);
                if (!absNegative.Equals((Double)abs))
                {
                    Console.WriteLine("Error_asd872!!! Abs ({0}, {1}) = {2} != Abs(-neg)={3}", real, imaginary, abs, absNegative);
                    Assert.True(false, "Verification Failed");
                }
            }
        }
Example #4
0
        /// <summary>
        /// Executes this Absolute expression.
        /// </summary>
        /// <param name="parameters">An object that contains all parameters and functions for expressions.</param>
        /// <returns>
        /// A result of the execution.
        /// </returns>
        /// <seealso cref="ExpressionParameters" />
        public override object Execute(ExpressionParameters parameters)
        {
            var result = m_argument.Execute(parameters);

            if (result is Complex complex)
            {
                return(Complex.Abs(complex));
            }

            if (result is Vector vector)
            {
                return(vector.Abs(parameters));
            }

            if (result is double number)
            {
                return(Math.Abs(number));
            }

            throw new ResultIsNotSupportedException(this, result);
        }
Example #5
0
        private double[] DFT(double[] image)
        {
            int N = Globals.Pixels;

            Complex[] x = new Complex[N];
            for (int i = 0; i < N; i++)
            {
                x[i] = new Complex(image[i], 0);
            }

            MathNet.Numerics.IntegralTransforms.Fourier.Forward(x);

            var amplitude = new double[N];

            for (int i = 0; i < N; i++)
            {
                amplitude[i] = Complex.Abs(x[i]);
            }

            return(amplitude);
        }
Example #6
0
        /// <param name="power">The power of sample points number. 2^(power)</param>
        public void GenerateLinearSweptSine(int power)
        {
            int signalLength    = (int)Math.Pow(2, power);
            int effectiveLength = signalLength / 2;

            Complex[] SweptSineFreq = new Complex[signalLength];
            for (int k = 0; k < signalLength / 2; k++)
            {
                double phase = 2.0 * Math.PI * effectiveLength * Math.Pow((double)k / signalLength, 2.0);
                SweptSineFreq[k] = new Complex(Math.Cos(phase), -1.0 * Math.Sin(phase));
            }
            for (int k = signalLength / 2; k < signalLength; k++)
            {
                double phase = 2.0 * Math.PI * effectiveLength * Math.Pow(1.0 - ((double)k / signalLength), 2.0);
                SweptSineFreq[k] = new Complex(Math.Cos(phase), Math.Sin(phase));
            }

            Fourier.Radix2Inverse(SweptSineFreq, FourierOptions.NoScaling);
            Complex[] SweptSineTime = new Complex[signalLength];
            Complex   Max           = new Complex();

            for (int k = 0; k < signalLength; k++)
            {
                SweptSineTime[k] = SweptSineFreq[(k + signalLength - (effectiveLength / 2)) % signalLength];
                if (Complex.Abs(SweptSineTime[k]) > Complex.Abs(Max))
                {
                    Max = SweptSineTime[k];
                }
            }

            int DataLength = SweptSineTime.Length * 2;

            _waveData = new double[1, DataLength];
            double Amp = 1.0 / Math.Abs(Max.Real);

            for (int datcnt = 0; datcnt < DataLength; datcnt++)
            {
                _waveData[0, datcnt] = Amp * SweptSineTime[datcnt % (DataLength / 2)].Real;
            }
        }
Example #7
0
    /// <summary>
    ///  This corrutine obtains these steps in order:
    ///  1) gets the data from the audiosource
    ///  2) displays the signal in time domain
    ///  3) displays the signal in FFT
    /// </summary>

    IEnumerator treatmentOfSound()
    {
        //ONE IS THE INPUT VALUES
        float[] samples = new float[windowSize];

        audioS.clip.GetData(samples, 0);


        //this is the window size
        for (int ii = 0; ii < windowSize; ii++)
        {
            X_inputValues[ii] = ii;
            Y_inputValues[ii] = (double)samples[ii];
        }


        //perform complex opterations and set up the arrays
        Complex[] inputSignal_Time  = new Complex[windowSize];
        Complex[] outputSignal_Freq = new Complex[windowSize];


        inputSignal_Time = FastFourierTransform.doubleToComplex(Y_inputValues);


        //result is the iutput values once FFT has been applied
        outputSignal_Freq = FastFourierTransform.FFT(inputSignal_Time, false);


        Y_output = new double[windowSize];
        //get module of complex number
        for (int ii = 0; ii < windowSize; ii++)
        {
            //Debug.Log(ii);
            Y_output[ii] = (double)Complex.Abs(outputSignal_Freq[ii]);
        }



        yield return(null);
    }
    static public void CalcMandelBrot(
        Bitmap bmp,
        double xCoordFrom, double yCoordFrom,
        double xCoordTo, double yCoordTo,
        Color[] palette)
    {
        int width  = bmp.Width;
        int height = bmp.Height;

        int iterMax = palette.Length;

        for (int x = 0; x < width; x++)
        {
            double xCoord = xCoordFrom + (xCoordTo - xCoordFrom) / width * x;
            for (int y = 0; y < height; y++)
            {
                double yCoord = yCoordFrom + (yCoordTo - yCoordFrom) / height * y;

                int cnt = 0;

                Complex c  = new Complex(xCoord, yCoord);
                Complex z  = new Complex(0, 0);
                Complex z2 = new Complex(0, 0);
                while ((z2.Abs() < 2.0) && (cnt < iterMax))
                {
                    z  = z2 + c;
                    z2 = z * z;
                    cnt++;
                }
                if (cnt == iterMax)
                {
                    bmp.SetPixel(x, y, Color.FromArgb(0, 0, 0));
                }
                else
                {
                    bmp.SetPixel(x, y, palette[cnt]);
                }
            }
        }
    }
        /// <summary>
        /// Symmetric elliptic integral of the first kind.
        /// </summary>
        public static Complex RF(Complex x, Complex y, Complex z)
        {
            switch ((x == 0 ? 1 : 0) + (y == 0 ? 1 : 0) + (z == 0 ? 1 : 0))
            {
            case 2:
                return(double.PositiveInfinity);
            }

            Complex
                A0 = (x + y + z) / 3,
                A  = A0;

            double
                r = 10 * Machine.ε,
                Q = Math.Pow(3 * r, -1 / 8d) * Math.Max(Math.Max(Complex.Abs(A - x), Complex.Abs(A - y)), Complex.Abs(A - z));

            while (Q >= Complex.Abs(A))
            {
                Complex
                    sx = Complex.Sqrt(x),
                    sy = Complex.Sqrt(y),
                    sz = Complex.Sqrt(z),
                    λ  = sx * sy + sy * sz + sz * sx;

                A  = (A + λ) / 4;
                x  = (x + λ) / 4;
                y  = (y + λ) / 4;
                z  = (z + λ) / 4;
                Q /= 4;
            }

            Complex
                X  = 1 - x / A,
                Y  = 1 - y / A,
                Z  = -X - Y,
                E2 = Z * Z - X * Y,
                E3 = X * Y * Z;

            return((1 + E3 * (1 / 14d + 3 * E3 / 104) + E2 * (1 / 10d + 3 * E3 / 44 + E2 * (1 / 24d + E3 / 16 + 5 * E2 / 208))) / Complex.Sqrt(A));
        }
Example #10
0
        private Complex RecursionProcedure(Func <Complex, Complex> integrand, double a, double b, Complex Sab, double tol, int trace)
        {
            double c = (a + b) / 2;

            Complex Sac = _quadr(integrand, a, c);
            Complex Scb = _quadr(integrand, c, b);

            if (Complex.Abs(Sab - Sac - Scb) <= tol)
            {
                return(Sac + Scb);
            }

            IterationsNeeded++;

            if (IterationsNeeded >= MaxIterations || trace <= 0)
            {
                throw new NotConvergenceException("Calculation does not converge to a solution.");
            }

            return(RecursionProcedure(integrand, a, c, Sac, tol / 2, trace - 1) +
                   RecursionProcedure(integrand, c, b, Scb, tol / 2, trace - 1));
        }
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            worker.WorkerSupportsCancellation = true;

            if (worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            else
            {
                for (Data.Fakt = Data.F1; Data.Fakt <= Data.F2; Data.Fakt++)
                {
                    Complex Xl_temp = new Complex(0, (2.0 * 3.14159265 * Data.Fakt * L / 1000));
                    Complex Xc_temp = new Complex(0, (-1 / (2.0 * 3.14159265 * Data.Fakt * C / 1000000)));
                    Complex Z_z     = new Complex(0, 0); Z_z = R1 + 1 / ((1 / Xc_temp) + (1 / R2) + (1 / Xl_temp));
                    Complex U1_z    = new Complex(Data.U1, 0);
                    Complex I1_z    = new Complex(0, 0); I1_z = U1_z / (Z_z);
                    Complex I3_z    = new Complex(0, 0); I3_z = I1_z * ((Xc_temp * R2) / (Xc_temp + R2)) / (((Xc_temp * R2) / (Xc_temp + R2)) + Xl_temp);
                    Complex U2_z    = new Complex(0, 0); U2_z = I3_z * Xl_temp;
                    Complex H_jw_z  = new Complex(0, 0); H_jw_z = U2_z / (1.0 * U1_z);

                    Dataseries1[0].Values.Add(new DataModelForChart {
                        Value_x = Data.Fakt, Value_y = Complex.Abs(H_jw_z)
                    });
                    Dataseries2[0].Values.Add(new DataModelForChart {
                        Value_x = Data.Fakt, Value_y = (H_jw_z.Phase * 180 / Math.PI)
                    });
                    Dataseries3[0].Values.Add(new DataModelForChart {
                        Value_x = Data.Fakt, Value_y = Complex.Abs(I1_z)
                    });

                    if (Data.Fakt == Data.F2)
                    {
                        worker.CancelAsync();                       // problemy z ostatnim punktem wykresu, dlatego taki dziwny zabieg
                    }
                }
            }
        }
Example #12
0
        public void JacobiArcsnComplexArgTest()
        {
            var z = new[]
            {
                new Complex(0.0115779438837883, 0.00215513498962569),
                new Complex(0.0251305156397967, -0.0159972042786677),
                new Complex(1.4511560737138, -0.480192562215063),
                new Complex(-1.8128943757431, 0.175402508876567),
                new Complex(0.974889810203627, 0.317370944403016),
            };

            var m = new[]
            {
                .82872474670,
                .95465479750,
                .41588039490,
                .79913716820,
                .22263345920,
            };

            var ans = new[] {
                "0.011577520035845973+0.002154873907338315 i",
                "0.02513162775967239-0.01598866500104887 i",
                "1.0366906460437097-0.0928117050540744 i",
                "-0.9833652385779392+0.0168760678403997 i",
                "0.8497782949947773+0.1722870976144199 i",
            };

            for (int i = 0; i < z.Length; i++)
            {
                var sn    = Parse(ans[i]);
                var arcsn = Jacobi.arcsn(sn, m[i]);
                var ex    = z[i];
                Assert.IsTrue(Complex.Abs(arcsn - ex) < 1e-14);
                var f  = Jacobi.arcsnComplex(m[i]);
                var a2 = f(sn);
                Assert.AreEqual(arcsn, a2);
            }
        }
Example #13
0
        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)));
        }
        /// <summary>Gets the complex roots of a polynomial with complex coefficients of degree 3.
        /// </summary>
        /// <param name="absoluteCoefficient">The absolute coefficient.</param>
        /// <param name="firstOrderCoefficient">The first order coefficient.</param>
        /// <param name="secondOrderCoefficient">The second order coefficient.</param>
        /// <param name="thirdOrderCoefficient">The third order coefficient.</param>
        /// <param name="firstRoot">The first root (output).</param>
        /// <param name="secondRoot">The second root (output).</param>
        /// <param name="thirdRoot">The third root (output).</param>
        /// <remarks>the implementation is based on §5.6, Numerical recipes, H. Press.</remarks>
        internal static void GetRoots(Complex absoluteCoefficient, Complex firstOrderCoefficient, Complex secondOrderCoefficient, Complex thirdOrderCoefficient, out Complex firstRoot, out Complex secondRoot, out Complex thirdRoot)
        {
            // normalized coefficients, i.e. x^3 + a * x^2 + b * x + c
            Complex a = secondOrderCoefficient / thirdOrderCoefficient;
            Complex b = firstOrderCoefficient / thirdOrderCoefficient;
            Complex c = absoluteCoefficient / thirdOrderCoefficient;

            Complex q = (a * a - 3.0 * b) / 9.0;
            Complex r = (2 * a * a * a - 9.0 * a * b + 27.0 * c) / 54.0;

            Complex sqrt = Complex.Sqrt(r * r - q * q * q);

            // compute the correct sign, i.e. such that \Re(r*sqrt) >= 0
            if ((r * sqrt).Real < 0)
            {
                sqrt *= -1.0;
            }

            /* Compute 'A = - (r + sqrt)^{1/3}', but keep in mind, that the cubic root is not unique defined.
             * In general, if z = r * e^{i t}, we have
             *
             * z^{1/3} = exp(1/3 * ln z)
             *         = r^{1/3} * exp(i*t/3), r^{1/3} * exp(i *(t/3 + 2\pi/3)), r^{1/3} * exp(i *(t/3 - 2\pi/3)).
             *
             * Here, we choose the first root.
             */
            Complex radicant = (r + sqrt);
            Complex A        = -Math.Pow(Complex.Abs(radicant), 1.0 / 3.0) * Complex.Exp(new Complex(0, Math.Atan2(radicant.Imaginary, radicant.Real) / 3.0));

            Complex B = (A == 0.0) ? 0.0 : q / A;  // It is not necessary to take into account any tolerance here

            firstRoot = (A + B) - a / 3.0;

            Complex firstRootPart  = -0.5 * (A + B) - a / 3.0;
            Complex secondRootPart = MathConsts.Sqrt3 / 2.0 * (A - B);

            secondRoot = new Complex(firstRootPart.Real - secondRootPart.Imaginary, firstRootPart.Imaginary + secondRootPart.Real);
            thirdRoot  = new Complex(firstRootPart.Real + secondRootPart.Imaginary, firstRootPart.Imaginary - secondRootPart.Real);
        }
Example #15
0
        public static Complex sqrt(object x)
        {
            Complex num = GetComplexNum(x);

            if (num.Imaginary() == 0.0)
            {
                if (num.Real >= 0.0)
                {
                    return(MathUtils.MakeReal(Math.Sqrt(num.Real)));
                }
                else
                {
                    return(MathUtils.MakeImaginary(Math.Sqrt(-num.Real)));
                }
            }

            double c    = num.Abs() + num.Real;
            double real = Math.Sqrt(0.5 * c);
            double imag = num.Imaginary() / Math.Sqrt(2 * c);

            return(new Complex(real, imag));
        }
Example #16
0
        public void JacobiArccnComplexArgTest()
        {
            var z = new[]
            {
                new Complex(0.0115779438837883, 0.00215513498962569),
                new Complex(0.0251305156397967, -0.0159972042786677),
                new Complex(2.12623597863526, 0.480192562215063),
                new Complex(1.8128943757431, -0.175402508876567),
                new Complex(0.974889810203627, 0.317370944403016),
            };

            var m = new[]
            {
                .8287247467,
                .9546547975,
                .4158803949,
                .7991371682,
                .2226334592,
            };

            var ans = new[] {
                "0.9999353004739177-0.0000249497100713 i",
                "0.9998120824513089+0.0004018967006233 i",
                "-0.2620696287961345-0.3671429875904256 i",
                "0.2003469806496059+0.0828329851756354 i",
                "0.6050679400137476-0.2419659452739375 i",
            };

            for (int i = 0; i < z.Length; i++)
            {
                var cn    = Parse(ans[i]);
                var arccn = Jacobi.arccn(cn, m[i]);
                var ex    = z[i];
                Assert.IsTrue(Complex.Abs(arccn - ex) < 1e-13);
                var f  = Jacobi.arccnComplex(m[i]);
                var a2 = f(cn);
                Assert.AreEqual(arccn, a2);
            }
        }
Example #17
0
        public static double Atan2(BigComplex y, BigComplex x)         // 2-argument arctangent
        {
            Complex a = new Complex((double)y.Real, (double)y.Imaginary);
            Complex b = new Complex((double)x.Real, (double)x.Imaginary);

            if (y.Sign > 0)
            {
                return(Complex.Abs(Complex.Atan(Complex.Divide(b, a))));
            }
            else if (y.Sign < 0 && x.Sign >= 0)
            {
                Complex tmp  = Complex.Atan(Complex.Divide(b, a));
                Complex tmp2 = new Complex(tmp.Real + Math.PI, tmp.Imaginary);
                return(Complex.Abs(tmp2));
            }
            else if (y.Sign < 0 && x.Sign < 0)
            {
                Complex tmp  = Complex.Atan(Complex.Divide(b, a));
                Complex tmp2 = new Complex(tmp.Real - Math.PI, tmp.Imaginary);
                return(Complex.Abs(tmp2));
            }
            else if (y.Sign == 0 && x.Sign > 0)
            {
                return(Math.PI / 2);
            }
            else if (y.Sign == 0 && x.Sign < 0)
            {
                return(-(Math.PI / 2));
            }
            else if (y.Sign == 0 && x.Sign == 0)
            {
                return(double.NaN);
            }
            else
            {
                return(double.NaN);
            }
        }
Example #18
0
        public void JacobiDnComplexArgTest()
        {
            var z = new[]
            {
                new Complex(0.0115779438837883, 0.00215513498962569),
                new Complex(0.0251305156397967, -0.0159972042786677),
                new Complex(2.12623597863526, 0.480192562215063),
                new Complex(-1.8128943757431, 0.175402508876567),
                new Complex(0.974889810203627, 0.317370944403016),
            };

            var m = new[]
            {
                .82872474670,
                .95465479750,
                .41588039490,
                .79913716820,
                .22263345920,
            };

            var ans = new[] {
                "0.9999463821545492-0.0000206762130171 i",
                "0.9998206008771541+0.0003836693444763 i",
                "0.7479880904783000+0.0534965402190790 i",
                "0.4777309286723279+0.0277602955990134 i",
                "0.9203769973939489-0.0354146592336434 i",
            };

            for (int i = 0; i < z.Length; i++)
            {
                var dn = Jacobi.dn(z[i], m[i]);
                var ex = Parse(ans[i]);
                Assert.IsTrue(Complex.Abs(dn - ex) < 1e-15);
                var f = Jacobi.dnComplex(m[i]);
                dn = f(z[i]);
                Assert.IsTrue(Complex.Abs(dn - ex) < 1e-15);
            }
        }
Example #19
0
        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));
        }
Example #20
0
        public void ReadHDF5FieldData()
        {
            double[,] re = HDF5.ReadFieldData2D(m_resultFile, "/nf2ff/E_theta/FD/f0_real");
            double[,] im = HDF5.ReadFieldData2D(m_resultFile, "/nf2ff/E_theta/FD/f0_imag");

            ETheta = new Complex[re.GetLength(0), re.GetLength(1)];
            for (int i = 0; i < re.GetLength(0); i++)
            {
                for (int j = 0; j < re.GetLength(1); j++)
                {
                    ETheta[i, j] = new Complex(re[i, j], im[i, j]);
                }
            }

            re = HDF5.ReadFieldData2D(m_resultFile, "/nf2ff/E_phi/FD/f0_real");
            im = HDF5.ReadFieldData2D(m_resultFile, "/nf2ff/E_phi/FD/f0_imag");

            EPhi = new Complex[re.GetLength(0), re.GetLength(1)];
            for (int i = 0; i < re.GetLength(0); i++)
            {
                for (int j = 0; j < re.GetLength(1); j++)
                {
                    EPhi[i, j] = new Complex(re[i, j], im[i, j]);
                }
            }

            ENorm = new double[re.GetLength(0), re.GetLength(1)];
            for (int i = 0; i < re.GetLength(0); i++)
            {
                for (int j = 0; j < re.GetLength(1); j++)
                {
                    ENorm[i, j] = Math.Sqrt(Complex.Abs(ETheta[i, j]) * Complex.Abs(ETheta[i, j])
                                            + Complex.Abs(EPhi[i, j] * Complex.Abs(EPhi[i, j])));
                }
            }

            PRadiated = HDF5.ReadFieldData2D(m_resultFile, "/nf2ff/P_rad/FD/f0");
        }
        private static List <IComplexTerm> GetPolynomialTerms(Complex value, Complex polynomialBase, int degree)
        {
            int                 d      = degree; // (int)Math.Truncate(Complex.Log(value, (double)polynomialBase)+ 1);
            Complex             toAdd  = value;
            List <IComplexTerm> result = new List <IComplexTerm>();

            while (d >= 0 && Complex.Abs(toAdd) > 0)
            {
                Complex placeValue = Complex.Pow(polynomialBase, d);

                if (placeValue == 1)
                {
                    result.Add(new ComplexTerm(toAdd, d));
                    toAdd = 0;
                }
                else if (placeValue == toAdd)
                {
                    result.Add(new ComplexTerm(1, d));
                    toAdd -= placeValue;
                }
                else if (Complex.Abs(placeValue) < Complex.Abs(toAdd))
                {
                    Complex quotient = Complex.Divide(toAdd, placeValue);
                    if (Complex.Abs(quotient) > Complex.Abs(placeValue))
                    {
                        quotient = placeValue;
                    }

                    result.Add(new ComplexTerm(quotient, d));
                    Complex toSubtract = Complex.Multiply(quotient, placeValue);

                    toAdd -= toSubtract;
                }

                d--;
            }
            return(result.ToList());
        }
Example #22
0
 public static void DropOutZeroFilt(Signal s)
 {
     if (s.Data.Count() > 0)
     {
         for (int idx = 0; idx < s.Data.Count; idx++)
         {
             if (s.Data[idx] < 1e-15)
             {
                 s.Flags[idx] = false;
             }
         }
     }
     else
     {
         for (int idx = 0; idx < s.ComplexData.Count; idx++)
         {
             if (Complex.Abs(s.ComplexData[idx]) == 0)
             {
                 s.Flags[idx] = false;
             }
         }
     }
 }
Example #23
0
        private static double[] GetPowerSpectrum(Complex[,] complices)
        {
            var yLength = complices.GetLength(0);
            var xLength = complices.GetLength(1);
            var array   = new double[xLength * yLength];
            var i       = 0;

            for (int y = 0; y < yLength; y++)
            {
                for (int x = 0; x < xLength; x++)
                {
                    array[i++] = Complex.Abs(complices[y, x]);
                }
            }

            var divisor = array.Max() * 255;

            foreach (ref var item in array.AsSpan())
            {
                item /= divisor;
            }
            return(array);
        }
Example #24
0
        public void EigenSystemTest()
        {
            //arrange
            int     size     = _m.RowCount;
            double  TOL      = 10E-13;
            CMatrix identity = CMatrix.Identity(size);

            //action
            CEigenproblem eigen     = new CEigenproblem(_m, true);
            CMatrix       eigenVals = eigen.Eigenvalues;
            CMatrix       eigenVecs = eigen.Eigenvectors;

            //assert
            for (int i = 0; i < size; i++)
            {
                CMatrix v = (_m - eigenVals[i] * identity) * eigenVecs.GetColumn(i);

                foreach (Complex elem in v)
                {
                    NumericUtil.FuzzyEquals(Complex.Abs(elem), 0, TOL).Should().BeTrue();
                }
            }
        }
Example #25
0
        public void Theta4DoubleTest()
        {
            var data = new[]
            {
                1, .8, 0.8713168498521653,
                .5, .8, 0.02201388267155668,
                .5, .5, 0.411526533253406,
            };

            for (int i = 0; i < data.Length; i += 3)
            {
                var z   = data[i];
                var q   = data[i + 1];
                var ex  = data[i + 2];
                var th  = Theta.θ4(z, q);
                var err = Complex.Abs(th - ex) / Complex.Abs(th);
                Assert.IsTrue(Complex.Abs(err) < 1e-15);
                var t3 = Theta.θ4DoubleForNome(q);
                th  = t3(z);
                err = Complex.Abs(th - ex) / Complex.Abs(th);
                Assert.IsTrue(Complex.Abs(err) < 1e-15);
            }
        }
Example #26
0
        public void Theta3DoubleTest()
        {
            var data = new[]
            {
                1, .8, 0.04246457514070379,
                .5, .8, 1.223823417425446,
                .5, .5, 1.484396862425167,
            };

            for (int i = 0; i < data.Length; i += 3)
            {
                var z   = data[i];
                var q   = data[i + 1];
                var ex  = data[i + 2];
                var th  = Theta.θ3(z, q);
                var err = Complex.Abs(th - ex) / Complex.Abs(th);
                Assert.IsTrue(Complex.Abs(err) < 1e-15);
                var t3 = Theta.θ3DoubleForNome(q);
                th  = t3(z);
                err = Complex.Abs(th - ex) / Complex.Abs(th);
                Assert.IsTrue(Complex.Abs(err) < 1e-15);
            }
        }
Example #27
0
        public void DivTest()
        {
            //arrange
            double TOL = 1E-12;

            CPolynomial f    = new CPolynomial(new Complex[] { new Complex(3467.2, 456), new Complex(2.225, -0.0123), new Complex(46.2, 4.24), new Complex(2, 2), new Complex(12.8, 16.3), new Complex(0, 0), new Complex(22, 347) });
            CPolynomial g    = new CPolynomial(new Complex[] { new Complex(3, 8.5), new Complex(11, -0.5), new Complex(0, 1), new Complex(1, 2), new Complex(346, 4.365) });
            CPolynomial zero = new CPolynomial(1);

            CPolynomial r;
            CPolynomial q     = CPolynomial.Divide(f, g, out r);
            CPolynomial rtest = new CPolynomial(1);

            //action
            CPolynomial qtest = CPolynomial.Divide(f - r, g, out rtest);

            //assert
            for (int j = 0; j < rtest.Length; j++)
            {
                Complex.Abs(rtest[j]).Should().BeLessOrEqualTo(TOL);
            }
            qtest.Should().Be(q);
        }
Example #28
0
        public object LogOp(object param)
        {
            if (param is Complex)
            {
                Complex complex = (Complex)param;
                return(new Complex(Math.Log10(complex.Abs()), complex.Arg()));
            }
            if (!(param is JepDouble))
            {
                throw new EvaluationException("Invalid parameter type");
            }
            double doubleValue = ((JepDouble)param).DoubleValue;

            if (doubleValue >= 0.0)
            {
                return(new JepDouble(Math.Log10(doubleValue)));
            }
            if (double.IsNaN(doubleValue))
            {
                return(new JepDouble(double.NaN));
            }
            return(new Complex(Math.Log10(-doubleValue), 3.1415926535897931));
        }
Example #29
0
        public void Theta4ComplexTest()
        {
            var data = new[]
            {
                1, .5, .8, .2, 0.11267273837782, 0.63114326027714,
                .5, 1, .8, .2, -149.86895286679, 53.695192284056,
                .5, 0, .5, .7, 0.5835418615326, -0.12747179582096,
            };

            for (int i = 0; i < data.Length; i += 6)
            {
                var z   = new Complex(data[i], data[i + 1]);
                var q   = new Complex(data[i + 2], data[i + 3]);
                var ex  = new Complex(data[i + 4], data[i + 5]);
                var th  = Theta.θ4(z, q);
                var err = Complex.Abs(th - ex) / Complex.Abs(th);
                Assert.IsTrue(Complex.Abs(err) < 1e-13);
                var t4 = Theta.θ4ComplexForNome(q);
                th  = t4(z);
                err = Complex.Abs(th - ex) / Complex.Abs(th);
                Assert.IsTrue(Complex.Abs(err) < 1e-13);
            }
        }
Example #30
0
        /// <summary>
        /// Computes the norm of a vector avoiding overflow, sqrt( x' * x ).
        /// </summary>
        public static double NormRobust(int n, Complex[] x)
        {
            double scale = 0.0, ssq = 1.0;

            for (int i = 0; i < n; ++i)
            {
                if (x[i] != 0.0)
                {
                    double absxi = Complex.Abs(x[i]);
                    if (scale < absxi)
                    {
                        ssq   = 1.0 + ssq * (scale / absxi) * (scale / absxi);
                        scale = absxi;
                    }
                    else
                    {
                        ssq += (absxi / scale) * (absxi / scale);
                    }
                }
            }

            return(scale * Math.Sqrt(ssq));
        }
Example #31
0
        private static int ClosestToUnitCircle(List <Complex> arr, Func <Complex, bool> condition)
        {
            var pos         = 0;
            var minDistance = double.MaxValue;

            for (var i = 0; i < arr.Count; i++)
            {
                if (!condition(arr[i]))
                {
                    continue;
                }

                var distance = Complex.Abs(Complex.Abs(arr[i]) - 1.0);

                if (distance < minDistance)
                {
                    minDistance = distance;
                    pos         = i;
                }
            }

            return(pos);
        }
Example #32
0
        // 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());
        }
Example #33
0
 public static int test(Complex z, Complex c)
 {
     for(int q = 0 ; q < 16 ; q++) {
         z = z * z + c;
         if(z.Abs() >= 2.0) return q;
     } return 16;
 }