ToString(string baseVariable) { StringBuilder builder = new StringBuilder(); for (int i = Order; i >= 0; i--) { Complex coeff = _coefficients[i]; if (coeff.IsZero) { continue; } if (!coeff.IsReal) { builder.Append(builder.Length > 0 ? " + (" : "("); builder.Append(coeff.ToString()); builder.Append(')'); } else { double realCoeff = coeff.Real; if (builder.Length > 0) { builder.Append(realCoeff > 0d ? " + " : " - "); } else { if (realCoeff < 0d) { builder.Append('-'); } } if (i == 0 || (!Number.AlmostEqual(realCoeff, 1) && !Number.AlmostEqual(realCoeff, -1))) { builder.Append(Math.Abs(realCoeff)); } } if (i > 0) { builder.Append(" " + baseVariable); } if (i > 1) { builder.Append('^'); builder.Append(i); } } if (builder.Length == 0) { builder.Append('0'); } return(builder.ToString()); }
/// <summary> /// Testing the method <see cref="Complex.ToString"/> /// </summary> [Test] public void ToStringTest() { for (int i = 0; i < 100; i++) { Complex c = new Complex(2 * random.NextDouble() - 1, 2 * random.NextDouble() - 1); string s = c.ToString(); Assertion.AssertEquals("#A00 Unexpected parse result.", c, Complex.Parse(s)); } }