/// <summary> /// Перемещение созданного вектора (и его создание, если таковой отсутствует) для области окружности /// </summary> /// <param name="start">Начало вектора</param> /// <param name="end">Конец вектора</param> /// <param name="V">Значение скорости</param> /// <param name="domain">Вид канонической области</param> /// <param name="w">Комплексный потенциал</param> public void RedrawArrow(Complex start, Complex end, Complex V, CanonicalDomain domain, Hydrodynamics_Sources.Potential w) { if (IsMouseClickedInPolygon || Complex.IsNaN(V)) { if (start.Abs < w.R || Complex.IsNaN(V)) { DeleteArrow(); IsMouseClickedInPolygon = false; } else { if (!HasArrow()) { CreateArrow(); } arrow.StartPoint = start; arrow.EndPoint = end; arrowText.Text = $"X: {start.Re.ToString(Settings.Format)}; Y: {start.Im.ToString(Settings.Format)};".Replace(',', '.') + $"\nVx: {V.Re.ToString(Settings.Format)}; Vy: {V.Im.ToString(Settings.Format)};".Replace(',', '.'); arrowText.TextPosition = (start + (V.Im >= 0 ? -1 : 0.2) * 1.2 * Complex.I); } } else { if (!HasArrow()) { CreateArrow(); } arrow.StartPoint = start; arrow.EndPoint = end; arrowText.Text = $"X: {start.Re.ToString(Settings.Format)}; Y: {start.Im.ToString(Settings.Format)};".Replace(',', '.') + $"\nVx: {V.Re.ToString(Settings.Format)}; Vy: {V.Im.ToString(Settings.Format)};".Replace(',', '.'); arrowText.TextPosition = (start + (V.Im >= 0 ? -1 : 0.2) * 1.2 * Complex.I); } }
private void PlotModel_MouseMove(object sender, OxyMouseEventArgs e) { CursorPosition = viewModel.GetComplexCursorPositionOnPlot(e.Position); if (w.f is Hydrodynamics_Sources.Conformal_Maps.Diffusor && CursorPosition.Im < 0) { V = w.V_physical_plane(CursorPosition.Conjugate); V = V.Conjugate; } else { V = w.V_physical_plane(CursorPosition); } if (w.f is Hydrodynamics_Sources.Conformal_Maps.EjectedRays && CursorPosition.Re < 0 && (Math.Abs(CursorPosition.Im) < CursorPosition.Re * Math.Tan((w.f as Hydrodynamics_Sources.Conformal_Maps.EjectedRays).Angle))) { V = -V; } if (w.f is Hydrodynamics_Sources.Conformal_Maps.EjectedRays && CursorPosition.Re < 0 && (w.f as Hydrodynamics_Sources.Conformal_Maps.EjectedRays).Angle == Mathematical_Sources.MathematicalConstants.PiDividedOnTwo) { V = -V; } if (Complex.IsNaN(V) || IsCursorInBorder()) { ClearTextBoxes(); return; } else { xTextBox.Text = CursorPosition.Re.ToString(Settings.Format); yTextBox.Text = CursorPosition.Im.ToString(Settings.Format); VxTextBox.Text = V.Re.ToString(Settings.Format); VyTextBox.Text = V.Im.ToString(Settings.Format); } }
private void PlotModel_MouseMove(object sender, OxyMouseEventArgs e) { #if !HELP_FOR_GROUP_LEADER CursorPosition = viewModel.GetComplexCursorPositionOnPlot(e.Position); if (w.f is Hydrodynamics_Sources.Conformal_Maps.IdentityTransform) { V = w.V_physical_plane(CursorPosition); if (Complex.IsNaN(V) || IsCursorInBorder()) { ClearTextBoxes(); return; } else { xTextBox.Text = CursorPosition.Re.ToString(Settings.Format); yTextBox.Text = CursorPosition.Im.ToString(Settings.Format); VxTextBox.Text = V.Re.ToString(Settings.Format); VyTextBox.Text = V.Im.ToString(Settings.Format); } } else { xTextBox.Text = CursorPosition.Re.ToString(Settings.Format); yTextBox.Text = CursorPosition.Im.ToString(Settings.Format); VxTextBox.Text = string.Empty; VyTextBox.Text = string.Empty; } #endif }
/// <summary>Checks a specified coefficient input. /// </summary> /// <param name="coefficient">The coefficient to check.</param> /// <param name="argumentName">The name of the argument.</param> /// <param name="errorMessage">The error message.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown, if <paramref name="coefficient"/> is not a number or +/- infinity.</exception> internal static void CheckCoefficient(Complex coefficient, string argumentName, string errorMessage) { if ((coefficient.IsNaN() == true) || Double.IsInfinity(coefficient.Real) || Double.IsInfinity(coefficient.Imaginary)) { throw new ArgumentOutOfRangeException(argumentName, String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ArgumentIsInvalid, errorMessage)); } }
/// <summary> /// Asserts that the expected value and the actual value are equal. /// </summary> /// <param name="expected">The expected value.</param> /// <param name="actual">The actual value.</param> public static void AreEqual(Complex expected, Complex actual) { if (expected.IsNaN() && actual.IsNaN()) { return; } if (expected.IsInfinity() && expected.IsInfinity()) { return; } bool pass = expected.Real.AlmostEqual(actual.Real); if (!pass) { Assert.Fail("Real components are not equal. Expected:{0}; Actual:{1}", expected.Real, actual.Real); } pass = expected.Imaginary.AlmostEqual(actual.Imaginary); if (!pass) { Assert.Fail("Imaginary components are not equal. Expected:{0}; Actual:{1}", expected.Imaginary, actual.Imaginary); } }
/// <summary> /// Returns the derivative of a complex function at a point x by Ridders' method of polynomial /// extrapolation. The value h is input as an estimated initial stepsize; it need not be small, but /// rather should be an increment in x over which func changes substantially. An estimate of the /// error in the derivative is returned as err. /// </summary> /// <param name="function">A target complex function.</param> /// <param name="difference">A complex function represents the difference quotient.</param> /// <param name="x">A point at which the derivative is calculated.</param> /// <param name="h">An estimated initial stepsize.</param> /// <param name="err">An estimate of the error.</param> /// <returns>Numerical approximation of the value of the derivative of function at point x.</returns> private static Complex RidersDerivation(Func <Complex, Complex> function, DifferenceQuotient difference, Complex x, double h, out double err) { if (Complex.IsNaN(function(x)) || Complex.IsInfinity(function(x))) { err = double.MaxValue; return(double.NaN); } int i, j; double errt, fac, hh; Complex ans = Complex.Zero; if (h == 0.0) { throw new ArgumentException("h must be nonzero."); } hh = h; a[0, 0] = difference(function, x, hh); err = big; for (i = 1; i < ntab; i++) { // Successive columns in the Neville tableau will go to smaller stepsizes and higher orders of // extrapolation. hh /= con; a[0, i] = difference(function, x, hh); // Try new, smaller stepsize. fac = con2; // Compute extrapolations of various orders, requiring no new function evaluations. for (j = 1; j <= i; j++) { a[j, i] = (a[j - 1, i] * fac - a[j - 1, i - 1]) / (fac - 1.0); fac = con2 * fac; errt = Math.Max(Complex.Abs(a[j, i] - a[j - 1, i]), Complex.Abs(a[j, i] - a[j - 1, i - 1])); // The error strategy is to compare each new extrapolation to one order lower, both // at the present stepsize and the previous one. // If error is decreased, save the improved answer. if (errt <= err) { err = errt; ans = a[j, i]; } } // If higher order is worse by a significant factor SAFE, then quit early. if (Complex.Abs(a[i, i] - a[i - 1, i - 1]) >= safe * err && err <= _tol * Complex.Abs(ans)) { return(ans); } } throw new NotConvergenceException("Calculation does not converge to a solution."); }
/// <summary> /// Returns the numerical value of the definite integral complex function of one variable. /// </summary> /// <returns>Approximate value of the definite integral.</returns> /// <exception cref="NotConvergenceException"> /// The algorithm does not converged for a certain number of iterations. /// </exception> public override Complex Integrate(Func <Complex, Complex> integrand, double lowerBound, double upperBound) { if (lowerBound == upperBound) { return(Complex.Zero); } double tol = Tolerance; // Testing the limits to infinity if (double.IsInfinity(lowerBound) || double.IsInfinity(upperBound)) { throw new NotConvergenceException("The limits of integration can not be infinite."); } Complex fa = integrand(lowerBound); Complex fb = integrand(upperBound); // Testing the endpoints to singularity if (Complex.IsInfinity(fa) || Complex.IsNaN(fa) || Complex.IsInfinity(fb) || Complex.IsNaN(fb)) { throw new NotConvergenceException("Calculation does not converge to a solution."); } R[0, 0] = 0.5 * (upperBound - lowerBound) * (integrand(lowerBound) + integrand(upperBound)); int n; for (n = 1; n < MaxIterations; n++) { double h = (upperBound - lowerBound) / Math.Pow(2.0, n); Complex sum = Complex.Zero; for (int k = 1; k <= Math.Pow(2, n - 1); k++) { sum += integrand(lowerBound + (2 * k - 1) * h); } R[n, 0] = 0.5 * R[n - 1, 0] + h * sum; for (int m = 1; m <= n; m++) { R[n, m] = R[n, m - 1] + (R[n, m - 1] - R[n - 1, m - 1]) / (Math.Pow(4, m) - 1); } double relativeError = Complex.Abs(R[n, n - 1] - R[n, n]); if (relativeError < tol) { IterationsNeeded = n; return(R[n, n]); } } throw new NotConvergenceException("Calculation does not converge to a solution."); }
public void CanDetermineIfNaN() { var complex = new Complex(double.NaN, 1); Assert.IsTrue(complex.IsNaN(), "Real part is NaN."); complex = new Complex(1, double.NaN); Assert.IsTrue(complex.IsNaN(), "Imaginary part is NaN."); complex = new Complex(double.NaN, double.NaN); Assert.IsTrue(complex.IsNaN(), "Both parts are NaN."); }
public void NaNTest() { var cd = new Complex(double.NaN, 1.1); Assert.IsTrue(cd.IsNaN()); cd = new Complex(1.1, double.NaN); Assert.IsTrue(cd.IsNaN()); cd = new Complex(1.1, 2.2); Assert.IsFalse(cd.IsNaN()); }
public static Complex Gamma(Complex z) { if (Complex.IsNaN(z)) { return(z); } if (z.Im == 0) { return(new Complex(Gamma(z.Re), 0)); } return(Exp(LnG(z))); }
public Complex[] Forward(Complex[] input, bool phaseShift = true) { var result = new Complex[input.Length]; var omega = (float)(-2.0 * Math.PI / input.Length); if (input.Length == 1) { result[0] = input[0]; if (Complex.IsNaN(result[0])) { return(new [] { new Complex(0, 0) }); } return(result); } var evenInput = new Complex[input.Length / 2]; var oddInput = new Complex[input.Length / 2]; for (var i = 0; i < input.Length / 2; i++) { evenInput[i] = input[2 * i]; oddInput[i] = input[2 * i + 1]; } var even = Forward(evenInput, phaseShift); var odd = Forward(oddInput, phaseShift); for (var k = 0; k < input.Length / 2; k++) { int phase; if (phaseShift) { phase = k - Size / 2; } else { phase = k; } odd[k] *= Complex.Polar(1, omega * phase); } for (var k = 0; k < input.Length / 2; k++) { result[k] = even[k] + odd[k]; result[k + input.Length / 2] = even[k] - odd[k]; } return(result); }
public static Complex[] FftDit1d(Complex[] input) { int N = input.Length; float omega = (float)(-2.0 * Math.PI / N); Complex[] result = new Complex[input.Length]; // base case if (N == 1) { result[0] = input[0]; if (Complex.IsNaN(result[0])) { return(new[] { new Complex(0, 0) }); } return(result); } // radix 2 Cooley-Tukey FFT if (N % 2 != 0) { throw new ArgumentException("N has to be the power of 2."); } Complex[] evenInput = new Complex[N / 2]; Complex[] oddInput = new Complex[N / 2]; for (int i = 0; i < N / 2; i++) { evenInput[i] = input[2 * i]; oddInput[i] = input[2 * i + 1]; } Complex[] even = FftDit1d(evenInput); Complex[] odd = FftDit1d(oddInput); for (int k = 0; k < N / 2; k++) { int phase = k; odd[k] *= Complex.FromPolar(1, omega * phase); } for (int k = 0; k < N / 2; k++) { result[k] = even[k] + odd[k]; result[k + N / 2] = even[k] - odd[k]; } return(result); }
public static void NaN() { Assert.True(Complex.IsNaN(new Complex(double.NaN, double.NaN))); Assert.True(Complex.IsNaN(new Complex(1, double.NaN))); Assert.True(Complex.IsNaN(new Complex(double.NaN, 1))); Assert.True(Complex.IsNaN(Complex.NaN)); Assert.False(Complex.IsNaN(new Complex(double.PositiveInfinity, double.NaN))); Assert.False(Complex.IsNaN(new Complex(double.NaN, double.PositiveInfinity))); Assert.False(Complex.IsNaN(Complex.Infinity)); VerifyRealImaginaryProperties(Complex.NaN, double.NaN, double.NaN); VerifyMagnitudePhaseProperties(Complex.NaN, double.NaN, double.NaN); }
private void PlotModel_MouseMove(object sender, OxyMouseEventArgs e) { CursorPosition = viewModel.GetComplexCursorPositionOnPlot(e.Position); V = w.V_physical_plane(CursorPosition); if (Complex.IsNaN(V) || IsCursorInBorder()) { ClearTextBoxes(); return; } else { xTextBox.Text = CursorPosition.Re.ToString(Settings.Format); yTextBox.Text = CursorPosition.Im.ToString(Settings.Format); VxTextBox.Text = V.Re.ToString(Settings.Format); VyTextBox.Text = V.Im.ToString(Settings.Format); } }
public static void AlmostEqual(Complex expected, Complex actual) { if (expected.IsNaN() && actual.IsNaN() || expected.IsInfinity() && expected.IsInfinity()) { return; } if (!expected.Real.AlmostEqual(actual.Real)) { Assert.Fail("Real components are not equal. Expected:{0}; Actual:{1}", expected.Real, actual.Real); } if (!expected.Imaginary.AlmostEqual(actual.Imaginary)) { Assert.Fail("Imaginary components are not equal. Expected:{0}; Actual:{1}", expected.Imaginary, actual.Imaginary); } }
private static void AssertBitwiseEqual(double expected, double actual) { ulong expectedBits = BitConverter.DoubleToUInt64Bits(expected); ulong actualBits = BitConverter.DoubleToUInt64Bits(actual); if (expectedBits == actualBits) { return; } if (Complex.IsNaN(expected) && Complex.IsNaN(actual)) { return; } throw new Xunit.Sdk.EqualException(expected, actual); }
/// <summary> /// Checks that the specified <see cref="Complex"/> /// instances are equal. /// </summary> /// <param name="expected">The expected complex.</param> /// <param name="actual">The actual complex.</param> /// <param name="delta">The required accuracy.</param> public static void AreEqual( Complex expected, Complex actual, double delta) { if (Complex.IsNaN(expected)) { Assert.IsTrue(Complex.IsNaN(actual)); } else { Assert.AreEqual(expected.Real, actual.Real, delta, String.Format("Unexpected real value.")); Assert.AreEqual(expected.Imaginary, actual.Imaginary, delta, String.Format("Unexpected imaginary value.")); } }
/// <summary> /// Перемещение созданного вектора (и его создание, если таковой отсутствует) /// </summary> /// <param name="start">Начало вектора</param> /// <param name="end">Конец вектора</param> /// <param name="V">Значение скорости</param> /// <param name="domain">Вид канонической области</param> public void RedrawArrow(Complex start, Complex end, Complex V, CanonicalDomain domain) { if (IsMouseClickedInPolygon || Complex.IsNaN(V)) { DeleteArrow(); IsMouseClickedInPolygon = false; } else { if (!HasArrow()) { CreateArrow(); } arrow.StartPoint = start; arrow.EndPoint = end; arrowText.Text = $"X: {start.Re.ToString(Settings.Format)}; Y: {start.Im.ToString(Settings.Format)};".Replace(',', '.') + $"\nVx: {V.Re.ToString(Settings.Format)}; Vy: {V.Im.ToString(Settings.Format)};".Replace(',', '.'); arrowText.TextPosition = (start + (V.Im >= 0? -1: 0.2) * (domain == CanonicalDomain.HalfPlane ? 0.6 : 1.2) * Complex.I); } }
/// <summary>Initializes a new instance of the <see cref="RealPolynomial"/> class. /// </summary> /// <param name="degree">The degree of the polynomial.</param> /// <param name="coefficients">The coefficients, where the null-based index corresponds to the power of the argument, i.e. starting from the absolute coefficient, first oder coefficient etc.</param> /// <exception cref="ArgumentNullException">Thrown, if <paramref name="coefficients"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown, if one of the coefficients is not a number or +/- infinity.</exception> /// <exception cref="ArgumentException">Thrown, if <paramref name="coefficients"/> does not represents a polynom of degree <paramref name="degree"/>.</exception> internal ComplexPolynomial(int degree, IList <Complex> coefficients) { if (coefficients == null) { throw new ArgumentNullException(nameof(coefficients), String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ArgumentNull, nameof(coefficients))); } m_Degree = degree; m_Coefficients = new Complex[degree + 1]; for (int j = degree; j >= 0; j--) { Complex coefficient = m_Coefficients[j] = coefficients[j]; if ((coefficient.IsNaN() == true) || Double.IsInfinity(coefficient.Real) || Double.IsInfinity(coefficient.Imaginary)) { throw new ArgumentOutOfRangeException(nameof(coefficients)); } } if (coefficients[degree].Equals(Complex.Zero) == true) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ArgumentIsInvalid, "0.0"), nameof(coefficients)); } }
public static Complex Digamma(Complex z) { bool biggerPI = false; if (Abs(z.ArgRadians) >= Math.PI) { z = z.Conjugate; biggerPI = true; } Complex s = 0, tmp = 10; for (int n = 1; ; n++) { s += BernulliNumber(2 * n) / (2 * n * Pow(z, 2 * n)); if (Abs(s.Re - tmp.Re) < Settings.Eps && Abs(s.Im - tmp.Im) < Settings.Eps) { s = Ln(z) - 1.0 / (2 * z) - s; if (biggerPI) { return(s.Conjugate); } else { return(s); } } if (Complex.IsNaN(s)) { return(Complex.Infinity); } if (n > 1000) { throw new ApplicationException("Can't calculate the digamma-function."); } tmp = s; } }
void CalculateLoadFlowForSubGraph(Node source, List <KeyValuePair <long, LoadFlowResult> > result) { Dictionary <long, LoadFlowResult> lf = new Dictionary <long, LoadFlowResult>(); EnergySource es = source.IO as EnergySource; if (es == null) { return; } Complex u1 = GetVoltageFromEnergySource(es); if (u1.IsNaN()) { return; } Dictionary <long, Complex> currents = new Dictionary <long, Complex>(); for (int iteration = 0; iteration < maxIterations; ++iteration) { double maxVoltageRelativeDelta = 0; Stack <Triple <Node, int, List <Complex> > > stack = new Stack <Triple <Node, int, List <Complex> > >(); stack.Push(new Triple <Node, int, List <Complex> >(source, 0, new List <Complex>(source.AdjacentCount - 1))); HashSet <long> visited = new HashSet <long>(); while (stack.Count > 0) { Triple <Node, int, List <Complex> > triple = stack.Pop(); Node node = triple.First; int childrenPos = triple.Second; Func <Node, IEnumerable <Complex>, Dictionary <long, LoadFlowResult>, Complex> currentFunction = CalculateCurrentDefault; visited.Add(node.IO.GID); DMSType type = ModelCodeHelper.GetTypeFromGID(node.IO.GID); switch (type) { case DMSType.Recloser: continue; case DMSType.ConnectivityNode: { LoadFlowResult lfr; if (!lf.TryGetValue(node.IO.GID, out lfr)) { lfr = new LoadFlowResult(); lfr.Add(new LoadFlowResultItem(u1.X, LoadFlowResultType.UR)); lfr.Add(new LoadFlowResultItem(u1.Y, LoadFlowResultType.UI)); lf[node.IO.GID] = lfr; } } break; case DMSType.EnergyConsumer: { currentFunction = CalculateCurrentForEnergyConsumer; LoadFlowResult lfr; if (!lf.TryGetValue(node.IO.GID, out lfr)) { Complex s = GetPowerForEnergyConsumer(node.IO as EnergyConsumer); lfr = new LoadFlowResult(); lfr.Add(new LoadFlowResultItem(s.X, LoadFlowResultType.SR)); lfr.Add(new LoadFlowResultItem(s.Y, LoadFlowResultType.SI)); lf[node.IO.GID] = lfr; } } break; case DMSType.Breaker: case DMSType.Disconnector: { currentFunction = CalculateCurrentForSwitch; if (childrenPos == 0) { double maxDelta = CalculateVoltageForSwitch(node, lf, currents); if (maxDelta > maxVoltageRelativeDelta) { maxVoltageRelativeDelta = maxDelta; } } } break; case DMSType.DistributionGenerator: { currentFunction = CalculateCurrentForDistributionGenerator; } break; case DMSType.TransformerWinding: { currentFunction = CalculateCurrentForTransformerWinding; if (childrenPos == 0) { double maxDelta = CalculateVoltageForTransformerWinding(node, lf, currents); if (maxDelta > maxVoltageRelativeDelta) { maxVoltageRelativeDelta = maxDelta; } } } break; case DMSType.ACLineSegment: { currentFunction = CalculateCurrentForACLineSegment; if (childrenPos == 0) { double maxDelta = CalculateVoltageForACLineSegment(node, lf, currents); if (maxDelta > maxVoltageRelativeDelta) { maxVoltageRelativeDelta = maxDelta; } } } break; } Node childNode = null; for (int i = node.AdjacentOffset + childrenPos; i < node.AdjacentOffset + node.AdjacentCount; ++i) { Node adjacentNode = adjacency[i]; if (adjacentNode == null || visited.Contains(adjacentNode.IO.GID)) { continue; } childNode = adjacentNode; break; } if (childNode != null) { stack.Push(new Triple <Node, int, List <Complex> >(node, childrenPos + 1, triple.Third)); stack.Push(new Triple <Node, int, List <Complex> >(childNode, 0, new List <Complex>(childNode.AdjacentCount - 1))); continue; } if (stack.Count > 0) { Complex current = currentFunction(node, triple.Third, lf); stack.Peek().Third.Add(current); currents[node.IO.GID] = current; } } if (maxVoltageRelativeDelta < voltageRelativeDelta) { break; } } result.AddRange(lf); }
private void FindRoot() { Complex res = Complex.NaN; #region prepare dform if (dForm == null) { dForm = new DekartForm(100, 100, 300, 300); dForm.ClientSize = new Size(600, 600); dForm.Use_IsVisible = false; dForm.FormClosed += new FormClosedEventHandler(delegate(object s, FormClosedEventArgs eva) { dForm = null; }); } else { dForm.RemoveAllGraphics(); } #endregion List <Root> roots = new List <Root>(); List <PointF> pts = new List <PointF>(); List <Color> colors = new List <Color>(); Color[] baseColors = new Color[] { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.LightBlue, Color.Blue, Color.Violet }; double y1 = x1, y2 = x2; DoubleOfVectorFunction[] dovf = new DoubleOfVectorFunction[] { f1, f2 }; Complex c = new Complex(0); for (double y = y1; y < y2; y += hy) { for (double x = x1; x < x2; x += hx) { int iterations; float percent; c.re = x; c.im = y; res = Newtone(dovf, c, eps, out iterations); bool inRange = true; inRange &= res.re > x1; inRange &= res.re < x2; inRange &= res.im > y1; inRange &= res.im < y2; if (Complex.IsNaN(res) || !inRange) { colors.Add(Color.Black); pts.Add(new PointF((float)x, (float)y)); } else { if (roots.Count == 0) { Root newRoot; newRoot.color = baseColors[roots.Count % baseColors.Length]; newRoot.value = res; roots.Add(newRoot); } percent = iterations / 15f; if (percent > 1f) { percent = 1f; } bool needAdd = true; foreach (Root r in roots) { if (Near(r.value, res)) { colors.Add(ColorModifer.Brightness(r.color, percent)); pts.Add(new PointF((float)x, (float)y)); needAdd = false; break; } } if (needAdd) { Root newRoot; newRoot.color = baseColors[roots.Count % baseColors.Length]; newRoot.value = res; roots.Add(newRoot); colors.Add(ColorModifer.Brightness(newRoot.color, percent)); pts.Add(new PointF((float)x, (float)y)); } } } } DotGraphic dotGraphic = new DotGraphic(pts.ToArray(), colors.ToArray()); dotGraphic.CurrentColorSchema = new MathGraphic.ColorSchema( Color.Black, Color.DimGray, Color.DimGray, Color.Gray); dForm.AddGraphic(dotGraphic); MathGraphic mg; mg = new MathGraphic(Color.White, DrawModes.DrawLines, f1x, f1y, -5f, 5f, 0.01f); dForm.AddGraphic(mg); mg = new MathGraphic(Color.White, DrawModes.DrawLines, f2x, f2y, -5f, 5f, 0.01f); dForm.AddGraphic(mg); dForm.Show(); dForm.Update2(); foreach (Root z in roots) { listRoots.Items.Add("z" + (listRoots.Items.Count + 1) + " = " + z.value.ToString("F6")); listY.Items.Add("f,g" + (listY.Items.Count + 1) + " = " + f1(z.value.re, z.value.im).ToString("F6") + ", " + f2(z.value.re, z.value.im).ToString("F6")); } }
public static bool cIsNan(Complex value) { return(Complex.IsNaN(value)); }
private void FindRoot() { DateTime begin = DateTime.Now; Complex res = Complex.NaN; listRoots.Items.Clear(); listY.Items.Clear(); List <Root> roots = new List <Root>(); Bitmap bitmap = new Bitmap(bgf.PictureWidth + 1, bgf.PictureHeight + 1, System.Drawing.Imaging.PixelFormat.Format24bppRgb); int ir = 0; Complex p0; double hx = (x2 - x1) / bgf.PictureWidth; // 0.01 double hy = (y2 - y1) / bgf.PictureHeight; // 0.01 if (hx < hy) { hx = hy; } else { hy = hx; } double x, y; x = x1; y = y1; for (int j = bitmap.Height - 1; j >= 0; y += hy, j--) { x = x1; for (int i = 0; i < bitmap.Width; x += hx, i++) { int iterations; p0.re = x; p0.im = y; res = NewtoneRafson(f, df, p0, eps, out iterations); if (Complex.IsNaN(res)) { bitmap.SetPixel(i, j, Color.Black); } else { if (roots.Count == 0) { Root newRoot; newRoot.value = res; roots.Add(newRoot); } bool needAdd = true; ir = 0; foreach (Root r in roots) { if (Near(r.value, res)) { bitmap.SetPixel(i, j, preColor[ir % baseColors.Length, iterations]); needAdd = false; break; } ir++; } if (needAdd) { Root newRoot; newRoot.value = res; roots.Add(newRoot); bitmap.SetPixel(i, j, preColor[roots.Count % baseColors.Length, iterations]); } } } } DateTime end = DateTime.Now; bgf.Text = end.Subtract(begin).ToString(); Graphics g = Graphics.FromImage(bitmap); g.SmoothingMode = SmoothingMode.HighQuality; ir = 0; foreach (Root r in roots) { float size1 = 3; int rx = (int)((r.value.re - x1) / hx); int ry = bitmap.Height - (int)((r.value.im - y1) / hy); g.FillEllipse( new SolidBrush( preColor[ir % baseColors.Length, MAX_ITERATIONS / 3]), rx - size1, ry - size1, size1 * 2, size1 * 2 ); float size2 = 6; g.DrawEllipse( new Pen( preColor[ir % baseColors.Length, MAX_ITERATIONS / 2]), rx - size2, ry - size2, size2 * 2, size2 * 2 ); ir++; } bgf.SetBitmap(bitmap); if (bgf.Visible) { bgf.Refresh(); } else { bgf.Show(); } foreach (Root z in roots) { listRoots.Items.Add("z" + (listRoots.Items.Count + 1) + " = " + z.value.ToString("F6")); listY.Items.Add("f" + (listY.Items.Count + 1) + " = " + poly1.Evaluate(z.value).ToString("F6")); } }
//odczyt oraz zapis wartości do obiektu klasy Parameters private void LoadData() { par = new Parameters(); //odczyt źródeł Complex foo = ReadData("E1"); if (Complex.IsNaN(foo)) { return; } par.E1 = foo.Re; foo = ReadData("E2"); if (Complex.IsNaN(foo)) { return; } par.E2 = foo.Re; foo = ReadData("freq"); if (Complex.IsNaN(foo)) { return; } par.f = foo.Re; //odczyt reaktancji I1 foo = ReadData("Z11"); if (Complex.IsNaN(foo)) { return; } par.Z10[0] = foo; foo = ReadData("Z12"); if (Complex.IsNaN(foo)) { return; } par.Z10[1] = foo; foo = ReadData("Z13"); if (Complex.IsNaN(foo)) { return; } par.Z10[2] = foo; //odczyt reaktancji I2 foo = ReadData("Z21"); if (Complex.IsNaN(foo)) { return; } par.Z20[0] = foo; foo = ReadData("Z22"); if (Complex.IsNaN(foo)) { return; } par.Z20[1] = foo; foo = ReadData("Z23"); if (Complex.IsNaN(foo)) { return; } par.Z20[2] = foo; //odczyt reaktancji I3 foo = ReadData("Z31"); if (Complex.IsNaN(foo)) { return; } par.Z30[0] = foo; foo = ReadData("Z32"); if (Complex.IsNaN(foo)) { return; } par.Z30[1] = foo; foo = ReadData("Z33"); if (Complex.IsNaN(foo)) { return; } par.Z30[2] = foo; //połączenie pojedyńczych reaktancji na każdej gałęzi par.Z1 = par.Z10[0] + par.Z10[1] + par.Z10[2]; par.Z2 = par.Z20[0] + par.Z20[1] + par.Z20[2]; par.Z3 = par.Z30[0] + par.Z30[1] + par.Z30[2]; CalculateResults(); }