From e0f2378c221b1899e4f1c6668c3a21e6d8a73f8d Mon Sep 17 00:00:00 2001 From: Tobias Glaubach Date: Tue, 17 Jul 2018 20:50:09 +0200 Subject: [PATCH] changed somne comments. improved the Trim implementation added a UnitTest for Trim --- src/Numerics.Tests/PolynomialTests.cs | 13 ++++++++++++ src/Numerics/Polynomial.cs | 29 +++++++++++---------------- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/Numerics.Tests/PolynomialTests.cs b/src/Numerics.Tests/PolynomialTests.cs index b4b78eba..342cf67a 100644 --- a/src/Numerics.Tests/PolynomialTests.cs +++ b/src/Numerics.Tests/PolynomialTests.cs @@ -210,6 +210,19 @@ namespace MathNet.Numerics.UnitTests } + [TestCase(new double[] { 5, 4, 0 }, "5 + 4x^1")] + [TestCase(new double[] { 0, 0, 0 }, "0")] + [TestCase(new double[] { 5, 4, 3, 0, 2 }, "5 + 4x^1 + 3x^2 + 0x^3 + 2x^4")] + [TestCase(new double[] { 0, 0, 8, 0, 0 }, "0 + 0x^1 + 8x^2")] + [TestCase(new double[] { 0, 4, 3, 0, 0 }, "0 + 4x^1 + 3x^2")] + public void TrimTest(double[] x, string expected) + { + var p = new Polynomial(x); + p.Trim(); + Assert.AreEqual(expected, p.ToString()); + + } + public void DivideLongTestScalar(Tuple inVals, Tuple expectedVals) { var p1 = new Polynomial(1.0d); diff --git a/src/Numerics/Polynomial.cs b/src/Numerics/Polynomial.cs index 3213a5b3..4992f1d0 100644 --- a/src/Numerics/Polynomial.cs +++ b/src/Numerics/Polynomial.cs @@ -93,8 +93,8 @@ namespace MathNet.Numerics /// var xP1 = new Polynomial(x, isFlip:true); /// var xP2 = new Polynomial(x, isFlip:false); /// - /// xP1: 5 x^3 + 4 x^2 + 3 x^2 + 0 x^1 + 2 - /// xP2: 2 x^3 + 0 x^2 + 3 x^2 + 4 x^1 + 5 + /// xP1: 2 + 0x^1 + 3x^2 + 4x^3 + 5x^4 + /// xP2: 5 + 4x^1 + 3x^2 + 0x^3 + 2x^4 /// /// /// Polynomial coefficiens as array @@ -120,22 +120,17 @@ namespace MathNet.Numerics /// public void Trim() { - int count = 0; - for (int ii = Degree - 1; ii >= 0; ii--) + int i = Degree - 1; + while (i >= 0 && Coeffs[i] == 0.0) + i--; + + if (i < 0) + Coeffs = new double[0]; + else { - if (Coeffs[ii] == 0.0) - { - count++; - } - else - { - double[] CoeffsHold = new double[Coeffs.Length]; - Coeffs.CopyTo(CoeffsHold, 0); - Array.Resize(ref CoeffsHold, Degree - count); - Coeffs = new double[Degree - count]; - CoeffsHold.CopyTo(Coeffs, 0); - return; - } + var hold = new double[i+1]; + Array.Copy(Coeffs, hold, i+1); + Coeffs = hold; } }