using System; using System.Collections.Generic; using System.Linq; using System.Text; using Azimuth.RootFinding; namespace Azimuth.UnitTests.RootFinding { public class NewtonsMethodTests : UnitTestSharp.TestFixture { public void Basic() { Scalar root; var success = NewtonsMethod.FindRoot(x => Math.Cos(x), x => -Math.Sin(x), 1, out root); CheckEqual(EndingState.SUCCESS, success); CheckEqual(Math.PI / 2, root); } public void NegativeMaxIterations() { Scalar root; int evaluations = 0; CheckThrow(typeof(Exception)); var success = NewtonsMethod.FindRoot(x => Math.Cos(x), x => -Math.Sin(x), 1, -1, out root, ref evaluations); } public void ZeroMaxIterations() { Scalar root; int evaluations = 0; CheckThrow(typeof(Exception)); var success = NewtonsMethod.FindRoot(x => Math.Cos(x), x => -Math.Sin(x), 1, 0, out root, ref evaluations); } public void ZeroDerivative() { Scalar root; var success = NewtonsMethod.FindRoot(x => 1 - x * x, x => -2 * x, 0, out root); CheckEqual(EndingState.MALFORMED_INPUT, success); Check(Scalar.IsNaN(root)); } public void Cycle() { Scalar root; int evaluations = 0; var success = NewtonsMethod.FindRoot(x => x*x*x-2*x+2, x => 3*x*x-2, 0, 64, out root, ref evaluations); CheckEqual(EndingState.MAX_ITERATIONS_EXCEEDED, success); Check(Scalar.IsNaN(root)); CheckEqual(64, evaluations); } public void ExactHit() { Scalar root; int evaluations = 0; var success = NewtonsMethod.FindRoot(x => x, x => 0, 0, 64, out root, ref evaluations); CheckEqual(EndingState.SUCCESS, success); CheckEqual(0, root); } } }