using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Azimuth.UnitTests.RootFinding { public class BisectionTests : UnitTestSharp.TestFixture { public class Polynomials : UnitTestSharp.TestFixture { public void Basic() { Scalar r1 = Azimuth.RootFinding.Bisection.FindRoot(x => x*(x+18)+17, new Interval(-400, -2)); Scalar r2 = Azimuth.RootFinding.Bisection.FindRoot(x => x * (x + 18) + 17, new Interval(-2, 7000)); CheckEqual(-17, r1); CheckEqual(-1, r2); } public void DoesNotStraddle() { CheckThrow(typeof(Exception)); Scalar r1 = Azimuth.RootFinding.Bisection.FindRoot(x => x * (x + 18) + 17, new Interval(-400, -401)); } public void MultipleRoots() { // Should give us the minimum root Scalar r1 = Azimuth.RootFinding.Bisection.FindRoot( x => (x + 3) * (x - 7) * (x - 4) * (x - 4) * (x - 4) * (x - 4) * (x + 2) * (x - 1) * (x - 3), new Interval(-400, 400)); var possibleRoots = new List(new Scalar[] { -3, 7, 4, -2, 1, 3 }); // There's no way to be sure which root the bisection will converge to. Check(possibleRoots.Contains(r1)); } public void InfinityBounds() { CheckThrow(typeof(Exception)); Scalar r1 = Azimuth.RootFinding.Bisection.FindRoot( x => (x + 3) * (x - 7) * (x - 4) * (x - 4) * (x - 4) * (x - 4) * (x + 2) * (x - 1) * (x - 3), new Interval(Scalar.NegativeInfinity, Scalar.PositiveInfinity)); } public void NonPolynomial() { var func = new Func(x => Math.Exp(x) - 0.5); Scalar r1 = Azimuth.RootFinding.Bisection.FindRoot(func, new Interval(-10, 10)); CheckEqual(Math.Log(0.5), r1); } public void Singularity() { var func = new Func(x => 1.0 / (x - 1.1)); Scalar r1 = Azimuth.RootFinding.Bisection.FindRoot(func, new Interval(-10, 10)); CheckEqual(1.1, r1); } } } }