Example #1
3
            // оператор + ____________________________________________________________________________________________



            // оператор - ____________________________________________________________________________________________
            public static Complex operator -(Complex FirstComplex, Complex SecondComplex)
            {
                if (FirstComplex.DNum != SecondComplex.DNum)
                {
                    int Temp;
                    Temp = FirstComplex.DNum;
                    FirstComplex.UNum *= SecondComplex.DNum;
                    FirstComplex.DNum *= SecondComplex.DNum;
                    SecondComplex.DNum *= Temp;
                    SecondComplex.UNum *= Temp;
                    Complex TEMP = new Complex(FirstComplex.UNum - SecondComplex.UNum, FirstComplex.DNum);
                    Console.WriteLine(FirstComplex.UNum);
                    Console.WriteLine(SecondComplex.UNum);
                    while (TEMP.DNum != 0 && TEMP.UNum != 0)
                    {
                        if (TEMP.DNum > TEMP.UNum)
                            TEMP.DNum %= TEMP.UNum;
                        else
                            TEMP.UNum %= TEMP.DNum;
                    }
                    Complex Result = new Complex((FirstComplex.UNum - SecondComplex.UNum) / Math.Abs(TEMP.DNum + TEMP.UNum), FirstComplex.DNum / Math.Abs(TEMP.DNum + TEMP.UNum));
                    return Result;
                }
                Complex ResultElse = new Complex(FirstComplex.UNum - SecondComplex.UNum, FirstComplex.DNum);
                return ResultElse;
            }
 public void SubtrachtTest()
 {
     calculator = new ComplexNumbers.Calculator();
     Complex<double> actual = calculator.Subtracht(new Complex<double>(4, 5), new Complex<double>(6, 7));
     Complex<double> expected = new Complex<double>(4 - 6, 5 - 7);
     Assert.True(actual.Equals(expected));
 }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the ComplexRational class,
 /// by directly referencing the two provided polynomial coefficients.
 /// </summary>
 public ComplexRational(
     Complex[] numeratorCoefficients,
     Complex[] denominatorCoefficients)
 {
     _numerator = new ComplexPolynomial(numeratorCoefficients);
     _denominator = new ComplexPolynomial(denominatorCoefficients);
 }
        public void TestDivision()
        {
            // 0/1
            Complex zeroDivOne = Complex.Zero / Complex.One;
            Assert.That(zeroDivOne.Real, Is.EqualTo(0), "Re{0/1} = 0");
            Assert.That(zeroDivOne.Imag, Is.EqualTo(0), "Im{0/1} = 0");

            // 1/0
            // TODO: verify this is really what should happen
            Complex oneDivZero = Complex.One / Complex.Zero;
            Assert.That(oneDivZero.Real, Is.EqualTo(double.PositiveInfinity), "Re{1/0} = infty");
            Assert.That(oneDivZero.Imag, Is.EqualTo(double.PositiveInfinity), "Im{1/0} = infty");

            // (1+2I)/(3+4I)
            Complex onePlus2I = new Complex(1, 2);
            Complex threePlus4I = new Complex(3, 4);
            Complex onPlus2IDivthreePlus4I = onePlus2I / threePlus4I;
            Assert.That(onPlus2IDivthreePlus4I.Real, Is.EqualTo(11d / 25d), "Re{(1+2I)/(3+4I)} = 11/25");
            Assert.That(onPlus2IDivthreePlus4I.Imag, Is.EqualTo(2d / 25d), "Im{(1+2I)/(3+4I)} = 2/25");

            // (big+big*I)/(2*big+2*big*I)
            const double big1 = double.MaxValue / 4;
            const double big2 = double.MaxValue / 2;
            Complex big1PlusBig1I = new Complex(big1, big1);
            Complex big2PlusBig2I = new Complex(big2, big2);
            Complex big1PlusBig1IDivBig2PlusBig2I = big1PlusBig1I / big2PlusBig2I;
            Assert.That(big1PlusBig1IDivBig2PlusBig2I.Real, Is.EqualTo(0.5), "Re{(big+big*I)/(2*big+2*big*I)} = 0.5");
            Assert.That(big1PlusBig1IDivBig2PlusBig2I.Imag, Is.EqualTo(0), "Im{((big+big*I)/(2*big+2*big*I)} = 0");
        }
Example #5
0
        /// <summary>
        /// Returns are much larger the real or imaginary part of a complex number.
        /// If the ratio of real and imaginary parts of complex number are not so large
        /// returns the initial value.
        /// </summary>
        /// <param name="value">A complex number.</param>
        /// <param name="complexThreshold">An integer representing the complex threshold.</param>
        /// <returns>
        /// Are much larger the real or imaginary part of the value.
        /// If the ratio of real and imaginary parts of the value are not so large
        /// returns the value.
        /// </returns>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// complexThreshold must be between 0 and 307.
        /// </exception>
        public static Complex ComplexThreshold(Complex value, int complexThreshold)
        {
            if (complexThreshold < 0 || complexThreshold > MaxComplexZeroThreshold)
                throw new ArgumentOutOfRangeException("complexThreshold", String.Format("Complex threshold must be between 0 and {0}.", MaxComplexZeroThreshold));

            if (value.IsReal || value.IsImaginary)
            {
                return value;
            }

            double d = Math.Pow(10, complexThreshold);

            double reAbs = Math.Abs(value.Re);
            double imAbs = Math.Abs(value.Im);

            if ((reAbs > imAbs) && (reAbs / imAbs > d))
            {
                return new Complex(value.Re, 0.0);
            }
            else if ((imAbs > reAbs) && (imAbs / reAbs > d))
            {
                return new Complex(0.0, value.Im);
            }

            return value;
        }
Example #6
0
 public static double Compute(Complex a, Complex b)
 {
   Complex temp = a * ComplexMath.Conjugate(a);
   temp += (b * ComplexMath.Conjugate(b));
   double ret = ComplexMath.Absolute(temp);
   return System.Math.Sqrt(ret);
 }
 public void MultiplyTest()
 {
     calculator = new ComplexNumbers.Calculator();
     Complex<double> actual = calculator.Multiply(new Complex<double>(4, 5), new Complex<double>(6, 7));
     Complex<double> expected = new Complex<double>(4 * 6 - 5 * 7, 5 * 6 + 4 * 7);
     Assert.True(actual.Equals(expected));
 }
Example #8
0
 private static bool IsConstant(string equation, int index, out string n, out Complex val)
 {
     var spi = Term.ExtractName(equation, index, false).ToLower();
     if (cs.Contains(spi, StringComparer.OrdinalIgnoreCase))
     {
         n = spi;
         var consts =
             typeof (Constants).GetProperties(BindingFlags.Public |
                                             BindingFlags.Static);
         if (
             consts.Any(
                 x =>
                     Attribute.IsDefined(x, typeof (MathConst)) &&
                     (Attribute.GetCustomAttribute(x, typeof (MathConst)) as MathConst).Name == spi.ToLower()))
         {
             var prop =
                 consts.First(
                     x =>
                         Attribute.IsDefined(x, typeof (MathConst)) &&
                         (Attribute.GetCustomAttribute(x, typeof (MathConst)) as MathConst).Name == spi.ToLower());
             val = (Complex) (prop.GetValue(null, null));
             return true;
         }
         else
         {
             val = double.NaN;
             return false;
         }
     }
     n = null;
     val = double.NaN;
     return false;
 }
        /// <summary>
        /// Does a point wise add of two arrays <c>z = x + y</c>. This can be used
        /// to add vectors or matrices.
        /// </summary>
        /// <param name="x">The array x.</param>
        /// <param name="y">The array y.</param>
        /// <param name="result">The result of the addition.</param>
        /// <remarks>There is no equivalent BLAS routine, but many libraries
        /// provide optimized (parallel and/or vectorized) versions of this
        /// routine.</remarks>
        public virtual void AddArrays(Complex[] x, Complex[] y, Complex[] result)
        {
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            if (x == null)
            {
                throw new ArgumentNullException("x");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (y.Length != x.Length || y.Length != result.Length)
            {
                throw new ArgumentException(NumericsResources.ArgumentVectorsSameLength);
            }

            CommonParallel.For(0, y.Length, 4096, (a, b) =>
            {
                for (int i = a; i < b; i++)
                {
                    result[i] = x[i] + y[i];
                }
            });
        }
        public override void FftKernel(Complex[] x, Complex[] y, int y0, int dy, int sign)
        {
            // all we have to do here is convolve (b x) with b-star
            // to do this convolution, we need to multiply the DFT of (b x) with the DFT of b-star, the IDFT the result back
            // we have already stored the DFT of b-star

            // create c = b x and transform it into Fourier space
            Complex[] c = new Complex[Nb];
            if (sign > 0) {
                for (int i = 0; i < R; i++) c[i] = b[i] * x[i];
            } else {
                for (int i = 0; i < R; i++) c[i] = b[i] * x[i].Conjugate;
            }
            Complex[] ct = ft.Transform(c);

            // multiply b-star and c = b x in Fourier space, and inverse transform the product back into configuration space
            for (int i = 0; i < Nb; i++) {
                ct[i] = ct[i] * bt[i];
            }
            c = ft.InverseTransform(ct);

            // read off the result
            if (sign > 0) {
                for (int i = 0; i < R; i++) y[y0 + i * dy] = b[i] * c[i];
            } else {
                for (int i = 0; i < R; i++) y[y0 + i * dy] = b[i].Conjugate * c[i].Conjugate;
            }

            // for the sign < 0 case, we have used the fact that the convolution of (b-star x) with b is
            // just the convolution of (b x-star) with b-star, starred
        }
Example #11
0
        public HComplex()
        {
            Value = new Complex(0, 0);

            Attributes.Add("real", new HassiumProperty("real", x => Real, (self, x) => Real = x[0].HDouble().Value));
            Attributes.Add("imaginary", new HassiumProperty("imaginary", x => Imaginary, (self, x) => Imaginary = x[0].HDouble().Value));
            Attributes.Add("imag", new HassiumProperty("imag", x => Imaginary, (self, x) => Imaginary = x[0].HDouble().Value));

            Attributes.Add("module", new HassiumProperty("module", x => (double)Value.Module, null, true));
            Attributes.Add("argument", new HassiumProperty("argument", x => (double)Value.Argument, null, true));
            Attributes.Add("conjugate", new HassiumProperty("conjugate", x => (double)Value.Conjugate, null, true));

            Attributes.Add("__add", new InternalFunction(Add, -1));
            Attributes.Add("__substract", new InternalFunction(Substract, -1));
            Attributes.Add("__multiply", new InternalFunction(Multiply, -1));
            Attributes.Add("__divide", new InternalFunction(Divide, -1));

            Attributes.Add("__compare", new InternalFunction(x =>
            {
                var v = x[0].HComplex().Value;
                if (v > Value) return 1;
                if (v < Value) return -1;
                return 0;
            }, 1));

            Attributes.Add("__pow", new InternalFunction(x => new HComplex(Functions.Pow(Value, x[0].HComplex().Value)), 1));
            Attributes.Add("__root", new InternalFunction(x => new HComplex(Functions.NthRoot(Value, x[0].HComplex().Value)), 1));

            Attributes.Add("negate", new InternalFunction(Negate, 0));

            Attributes.Add("square", new InternalFunction(x => new HComplex(Value.Square()), 0));
        }
 public void AddTest()
 {
     calculator = new ComplexNumbers.Calculator();
     Complex<double> actual = calculator.Add(new Complex<double>(4, 5), new Complex<double>(6, 7));
     Complex<double> expected = new Complex<double>(4 + 6, 5 + 7);
     Assert.True(actual.Equals(expected));
 }
Example #13
0
        static void Main()
        {
            //try
            //{
            //    string input;
            //    while ((input = Console.ReadLine()) != "exit")
            //        new Calculator(input);
            //}
            //catch (IndexOutOfRangeException)
            //{
            //    Console.WriteLine("Incorrect input");
            //}

            string str;
            var matrix = new Complex[2][];
            matrix[0] = new Complex[2];
            matrix[1] = new Complex[2];
            for (int i = 0; i < 2; i++)
                for (int j = 0; j < 2; j++)
                {
                    str = Console.ReadLine();
                    double a, b;
                    double.TryParse(str, out a);
                    str = Console.ReadLine();
                    double.TryParse(str, out b);
                    matrix[i][j] = new Complex(a, b);
                }
            var m = new Matrix<Complex>(matrix);
            var result = m + m;
            result.Print();
        }
        Task CalculateMandelbrotAsync(BmpMaker bmpMaker)
        {
            return Task.Run(() =>
            {
                for (int row = 0; row < pixelHeight; row++)
                {
                    double y = center.Imaginary - size.Height / 2 + row * size.Height / pixelHeight;

                    for (int col = 0; col < pixelWidth; col++)
                    {
                        double x = center.Real - size.Width / 2 + col * size.Width / pixelWidth;
                        Complex c = new Complex(x, y);
                        Complex z = 0;
                        int iteration = 0;

                        do
                        {
                            z = z * z + c;
                            iteration++;
                        }
                        while (iteration < iterations && z.MagnitudeSquared < 4);

                        bool isMandelbrotSet = iteration == iterations;
                        bmpMaker.SetPixel(row, col, isMandelbrotSet ? Color.Black : Color.White);
                    }
                }
            });
        }
		public static double[] padded_IFFT(ref Complex[] @in, bool doProperScaling=false)
		{
			Debug.Assert(@in.Length > 1);
			
			int originalLength = @in.Length;
			int n = (@in.Length - 1) * 2;
			
			int padded = n > 256 ? Util.NextLowPrimes(n) : n;

			Array.Resize<Complex>(ref @in, padded / 2 + 1);
			
			// prepare the input arrays
			var complexDouble = FFTUtils.ComplexToComplexDouble(@in);
			var fftwBackwardInput = new FFTW.ComplexArray(complexDouble);
			var fftwBackwardOutput = new FFTW.DoubleArray(padded);
			
			// this method needs that the backwards transform uses the output.length as it's N
			// i.e. FFTW.dft_c2r_1d(output.Length, input.Handle, output.Handle, Flags.Estimate);
			FFTW.BackwardTransform(fftwBackwardInput, fftwBackwardOutput);
			
			double[] @out = null;
			if (doProperScaling) {
				@out = fftwBackwardOutput.ValuesDivedByN;
			} else {
				// in the original method it wasn't scaled correctly (meaning ValuesDivedByN)
				@out = fftwBackwardOutput.Values;
			}
			
			Array.Resize<Complex>(ref @in, n / 2 + 1);
			
			// free up memory
			GC.Collect();

			return @out;
		}
Example #16
0
        /// <summary>
        /// Initializes a new instance of the CEigenproblem class, computing
        /// the eigenvalues and optionally the right eigenvectors of a square complex matrix.
        /// </summary>
        /// <param name="matrix">A complex square matrix.</param>
        /// <param name="rightEigenvectors">A value that indicating whether the right eigenvectors will be computed.</param>
        public CEigenproblem(CMatrix matrix, bool rightEigenvectors)
        {
            if (!matrix.IsSquare)
                throw new MatrixSizeMismatchException("The matrix must be square.");

            var order = matrix.RowCount;

            // Initialize matrices for eigenvalues and eigenvectors
            var eigenVectors = new Complex[order * order];
            var blockDiagonal = new Complex[order * order];
            var eigenValues = new Complex[order];

            new ManagedLinearAlgebraProvider().EigenDecomp(matrix.IsHermitian(), order, matrix.To1DimArray(), eigenVectors, eigenValues, blockDiagonal);

            _vals = eigenValues;

            _rightvecs = new CMatrix(matrix.RowCount, matrix.ColumnCount);
            for (int i = 0; i < matrix.RowCount; i++)
            {
                for (int j = 0; j < matrix.ColumnCount; j++)
                {
                    _rightvecs[i, j] = eigenVectors[j * matrix.RowCount + i];
                }
            }
        }
Example #17
0
 /// <summary>
 /// Вычисление ФФТ с переставленным массивом
 /// </summary>
 private static void _FFT(ref Complex[] revData, bool Reverse)
 {
     int Size = revData.Length;
     Complex W = new Complex();
     double pi2 = -Math.PI * 2;
     if (Reverse) pi2 = -pi2;
     for (int N = 2; N <= Size; N <<= 1)
     {
         double dn = pi2 / N;
         for (int i = 0; i < N / 2; i++)
         {
             double x = i * dn;
             W = new Complex((float)Math.Cos(x), (float)Math.Sin(x));
             //W = Complex.Exp(c01 * (pi2 * i / N));
             for (int j = i, s = i + N / 2; j < Size; j += N, s += N)
             {
                 Complex t = W * revData[s];
                 revData[s] = revData[j] - t;
                 revData[j] = revData[j] + t;
             }
         }
     }
     if (Reverse)
     {
         for (int i = 0; i < Size; i++)
         {
             revData[i].re /= Size;
             revData[i].im /= Size;
         }
     }
 }
Example #18
0
        /// <summary>
        /// Initializes a new instance of the CSVD class,
        /// computing the Singular Value Decomposition of a general complex matrix,
        /// with the possibility of computing only the singular values.
        /// </summary>
        /// <param name="matrix">A general complex matrix.</param>
        /// <param name="singularValuesOnly">A value that indicating whether only the singular values will be computed.</param>
        public CSVD(CMatrix matrix, bool singularValuesOnly)
        {
            _m = matrix.RowCount;
            _n = matrix.ColumnCount;

            var nm = Math.Min(matrix.RowCount, matrix.ColumnCount);
            var s = new Complex[nm];
            var u = new Complex[matrix.RowCount * matrix.RowCount];
            var vt = new Complex[matrix.ColumnCount * matrix.ColumnCount];

            new ManagedLinearAlgebraProvider().SingularValueDecomposition(!singularValuesOnly, matrix.To1DimArray(), matrix.RowCount, matrix.ColumnCount, s, u, vt);

            _s = s.ToArray().Select(x => x.Re).ToArray();

            _u = new CMatrix(matrix.RowCount, matrix.RowCount);
            for (int i = 0; i < matrix.RowCount; i++)
            {
                for (int j = 0; j < matrix.RowCount; j++)
                {
                    _u[i, j] = u[j * matrix.RowCount + i];
                }
            }

            _vt = new CMatrix(matrix.ColumnCount, matrix.ColumnCount);
            for (int i = 0; i < matrix.ColumnCount; i++)
            {
                for (int j = 0; j < matrix.ColumnCount; j++)
                {
                    _vt[i, j] = vt[j * matrix.ColumnCount + i];
                }
            }
        }
 public void DivideTest()
 {
     calculator = new ComplexNumbers.Calculator();
     Complex<double> actual = calculator.Divide(new Complex<double>(4, 5), new Complex<double>(6, 7));
     Complex<double> expected = new Complex<double>((4.0 * 6.0 + 5.0 * 7.0) / (6.0 * 6.0 + 7.0 * 7.0), (5.0 * 6.0 - 4.0 * 7.0) / (6.0 * 6.0 + 7.0 * 7.0));
     Assert.True(actual.Equals(expected));
 }
        /// <summary>
        /// Returns a vector of approximate values of roots of a complex polynomial by companion matrix method.
        /// </summary>
        /// <param name="poly">A complex polynomial.</param>
        /// <returns>The approximate values of roots of poly.</returns>
        /// <exception cref="System.ArgumentException">
        /// Number of elements in coeffs is less than 2 or more than 99.
        /// </exception>
        public static Complex[] CompanionMatrixRootsFinding(this CPolynomial poly)
        {
            // Remove zero elements standing at the end.
            int lidx = 0;
            int ridx = poly.Length - 1;
            while (ridx >= 0 && poly[ridx] == Complex.Zero) ridx--;
            while (lidx < poly.Length && poly[lidx] == Complex.Zero) lidx++;
            int length = ridx + 1;

            if (length < 2 || length > 99)
                throw new ArgumentException("Number of coefficients must be between 1 and 100.");

            int rootsCount = length - 1;
            Complex[] roots = new Complex[rootsCount];

            int n = ridx - lidx;
            CMatrix companionMatrix = new CMatrix(n, n);

            for (int i = 1; i < n; i++)
                companionMatrix[i, i - 1] = Complex.One;

            for (int i = 0; i < n; i++)
                companionMatrix[i, n - 1] = -poly[lidx + i] / poly[ridx];

            CMatrix eigenvals = CMatrix.Eigenvalues(companionMatrix);

            for (int i = 0; i < n; i++)
                roots[i] = eigenvals[i];

            Array.Sort<Complex>(roots, new ComplexComparer());
            return roots;
        }
 public void Equals()
 {
     Complex<double> actual = new Complex<double>(1, 2);
     Complex<double> expected = new Complex<double>(2, 3);
     Assert.True(actual.Equals(actual));
     Assert.AreEqual(actual.Equals(expected), expected.Equals(actual));
 }
Example #22
0
 private void Draw()
 {
     Complex p = new Complex(0, 0, true);
     Complex q = new Complex(0, 0, true);
     double t = 2.0 * Math.PI / (fx / 1.25);
     Color pc, qc, c;
     int r = 0, g = 0, b = 0;
     for(int x = 0 ; x < fx ; x++) {
         p.cis(0.99, t * x);
         pc = Color.FromArgb(p.c);
         for(int y = 0 ; y < fy ; y++) {
             q.cis(0.99, t * y);
             qc = Color.FromArgb(q.c);
             //r = (int)(255.0 * ((pc.R / 255.0) * (qc.R / 255.0)));
             //g = (int)(255.0 * ((pc.G / 255.0) * (qc.G / 255.0)));
             //b = (int)(255.0 * ((pc.B / 255.0) * (qc.B / 255.0)));
             //r = (x > fx / 5 * 2) ? 0 : pc.R ^ qc.R;
             //g = (x < fx / 5 * 1 || x > fx / 5 * 4) ? 0 : pc.G ^ qc.G;
             //b = (x < fx / 5 * 3) ? 0 : pc.B ^ qc.B;
             r = pc.R ^ qc.R;
             g = pc.G ^ qc.G;
             b = pc.B ^ qc.B;
             c = Color.FromArgb(255, r, g, b);
             gi.SetPixel(x, y, c);
         }
         gf.DrawLine(new Pen(pc), x, 0, x, fy);
     }
     gf.DrawImage(gi, 0, 0);
 }
        /// <summary>
        /// Applies the Discrete Fourier Transform to an input signal
        /// </summary>
        /// <param name="_inputSignal">The input signal of complex-valued amplitudes for each time sample</param>
        /// <param name="_outputSpectrum">The output complex-valued spectrum of amplitudes for each frequency.
        /// The spectrum of frequencies goes from [-N/2,N/2[ hertz, where N is the length of the input signal</param>
        /// <remarks>Throws an exception if signal and spectrum sizes mismatch and if their size are not a power of two!</remarks>
        public static void DFT_Forward( Complex[] _inputSignal, Complex[] _outputSpectrum )
        {
            int	size = _inputSignal.Length;
            if ( _outputSpectrum.Length != size )
                throw new Exception( "Input signal and output spectrum sizes mismatch!" );
            float	fPOT = (float) (Math.Log( size ) / Math.Log( 2.0 ));
            int		POT = (int) Math.Floor( fPOT );
            if ( fPOT != POT )
                throw new Exception( "Input signal length is not a Power Of Two!" );

            int		halfSize = size >> 1;
            double	normalizer = 1.0 / size;
            for ( int frequencyIndex=0; frequencyIndex < size; frequencyIndex++ ) {
                double	frequency = 2.0 * Math.PI * frequencyIndex;
                double	normalizedFrequency = -frequency * normalizer;	// Notice the - sign here! It's indicating the "division" by e^ix and the forward transform...

                // Accumulate (co)sine wave amplitude for specified frequency (i.e. computes how much the (co)sine wave matches to the signal at this frequency)
                double	sumR = 0.0;
                double	sumI = 0.0;
                for ( int i=0; i < size; i++ ) {
                    double	omega = i * normalizedFrequency;
                    double	c = Math.Cos( omega );
                    double	s = Math.Sin( omega );
                    Complex	v = _inputSignal[i];
                    sumR += c * v.r - s * v.i;
                    sumI += s * v.r + c * v.i;
                }
                sumR *= normalizer;
                sumI *= normalizer;
                _outputSpectrum[frequencyIndex].Set( sumR, sumI );
            }
        }
        public Task<BitmapInfo> CalculateAsync(Complex Center, 
                                               double width, double height,
                                               int pixelWidth, int pixelHeight, 
                                               int iterations,
                                               IProgress<double> progress, 
                                               CancellationToken cancelToken)
        {
            return Task.Run(() =>
            {
                int[] iterationCounts = new int[pixelWidth * pixelHeight];
                int index = 0;

                for (int row = 0; row < pixelHeight; row++)
                {
                    progress.Report((double)row / pixelHeight);
                    cancelToken.ThrowIfCancellationRequested();

                    double y = Center.Imaginary - height / 2 + row * height / pixelHeight;

                    for (int col = 0; col < pixelWidth; col++)
                    {
                        double x = Center.Real - width / 2 + col * width / pixelWidth;
                        Complex c = new Complex(x, y);

                        if ((c - new Complex(-1, 0)).MagnitudeSquared < 1.0 / 16)
                        {
                            iterationCounts[index++] = -1;
                        }
                        // http://www.reenigne.org/blog/algorithm-for-mandelbrot-cardioid/
                        else if (c.MagnitudeSquared * (8 * c.MagnitudeSquared - 3) < 3.0 / 32 - c.Real)
                        {
                            iterationCounts[index++] = -1;
                        }
                        else
                        {
                            Complex z = 0;
                            int iteration = 0;

                            do
                            {
                                z = z * z + c;
                                iteration++;
                            }
                            while (iteration < iterations && z.MagnitudeSquared < 4);

                            if (iteration == iterations)
                            {
                                iterationCounts[index++] = -1;
                            }
                            else
                            {
                                iterationCounts[index++] = iteration;
                            }
                        }
                    }
                }
                return new BitmapInfo(pixelWidth, pixelHeight, iterationCounts);
            }, cancelToken);
        }
Example #25
0
        public static void Test()
        {
            Complex cmplx = new Complex();
            cmplx = Complex.Rect(3, 5);
            Console.WriteLine(cmplx.RealPart + ", " + cmplx.ImaginaryPart);

            Console.Read();
        }
Example #26
0
 internal static int Compute( int m, int n, int k, Complex[] A, int lda, Complex[] tau ){
   ArgumentCheck(m, n, k, A, lda, tau);
   if (tau.Length < System.Math.Max(1, k) ){
     throw new ArgumentException("tau must be at least max(1,k).");
   }
   
   return dna_lapack_zungqr(Configuration.BlockSize, m, n, k, A, lda, tau);
 }
Example #27
0
 /// <summary>
 /// Copies an array of <see cref="Complex" /> elements into an array of the real part values and an array of the imaginary part values.
 /// </summary>
 /// <param name="src">The source array.</param>
 /// <param name="destreal">The array where the real part values are stored into.</param>
 /// <param name="destimag">The destination array where the imaginary part values are stored into.</param>
 /// <param name="n">The number of elements to copy. The copying is done from index 0 to n-1.</param>
 public static void CopyFromComplexToSplittedArrays(Complex[] src, double[] destreal, double[] destimag, int n)
 {
   for(int i=0;i<n;i++)
   {
     destreal[i]=src[i].Re;
     destimag[i]=src[i].Im;
   }
 }
Example #28
0
 /// <summary>
 /// Copies two arrays with real and imaginary part values into an array of <see cref="Complex" /> values.
 /// </summary>
 /// <param name="srcreal">The source array containing the real part values.</param>
 /// <param name="srcimag">The source array containing the imaginary part values.</param>
 /// <param name="dest">The destination array.</param>
 /// <param name="n">The number of elements to copy. The copying is done from index 0 to n-1.</param>
 public static void CopyFromSplittedArraysToComplex(double[] srcreal, double[] srcimag, Complex[] dest, int n)
 {
   for(int i=0;i<n;i++)
   {
     dest[i].Re = srcreal[i];
     dest[i].Im = srcimag[i];
   }
 }
Example #29
0
 static void Main(string[] args)
 {
     Complex FirstPair = new Complex(1, 2);
     Complex SecondPair = new Complex(1, 4);
     Complex Res = FirstPair * SecondPair;
     Console.WriteLine(Res);
     Console.ReadKey();
 }
Example #30
0
 public HMM()
 {
     State = new State();
     Observed = new Observed();
     InitialState = new InitialStateProbability();
     Transition = new Transition();
     Complex = new Complex();
 }