public void HalleyTest() { foreach (TestData d in _FunctionData) { double relTolerance = RootFinder.DefaultRelTolerance; double absTolerance = d.AbsTolerance; RootResults results = RootFinder.Halley(d.FuncVal_Der1_Der2, d.Guess, d.Min, d.Max, relTolerance, absTolerance, RootFinder.DefaultIterations); double solution = (results == null) ? double.NaN : results.SolutionX; if (!AreNear(solution, d.Expected, relTolerance, absTolerance)) { throw new AssertFailedException(" Halley Solve: (" + d.Description + ") = " + d.Expected + "; got " + solution + " Tolerance: " + d.RelTolerance); } } foreach (TestData d in testUnbracketedData) { double relTolerance = RootFinder.DefaultRelTolerance; double absTolerance = d.AbsTolerance; RootResults results = RootFinder.Halley(d.FuncVal_Der1_Der2, d.Guess, d.Min, d.Max, relTolerance, absTolerance, RootFinder.DefaultIterations); double solution = (results == null) ? double.NaN : results.SolutionX; if (!AreNear(solution, d.Expected, relTolerance, absTolerance)) { throw new AssertFailedException(" Halley Solve: (" + d.Description + ") = " + d.Expected + "; got " + solution + " Tolerance: " + d.RelTolerance); } } }
public void BrentTest() { foreach (TestData d in _FunctionData) { double relTolerance = RootFinder.DefaultRelTolerance; double absTolerance = d.AbsTolerance; var tol = RootFinder.GetToleranceFunc(RootFinder.DefaultRelTolerance, d.AbsTolerance); RootResults results = RootFinder.Brent(d.FuncValue, d.Min, d.Max, relTolerance, absTolerance, RootFinder.DefaultIterations); double solution = (results == null) ? double.NaN : results.SolutionX; if (!AreNear(solution, d.Expected, relTolerance, absTolerance)) { throw new AssertFailedException(" Brent Solve: (" + d.Description + ") = " + d.Expected + "; got " + solution + " Tolerance: " + d.RelTolerance); } results = RootFinder.BrentBracket(d.FuncValue, d.Guess, d.Step, FunctionShape.Unknown, d.Lmin, d.Lmax, relTolerance, absTolerance, RootFinder.DefaultIterations); solution = (results == null) ? double.NaN : results.SolutionX; if (!AreNear(solution, d.Expected, relTolerance, absTolerance)) { throw new AssertFailedException(" Brent Solve: (" + d.Description + ") = " + d.Expected + "; got " + solution + " Tolerance: " + d.RelTolerance); } } }
public static double SolveB(double a, double x, double p, double q, double guess, double step, double lower, double upper) { Func <double, double> f; if (p <= q) { f = b => Math2.Ibeta(a, b, x) - p; } else { f = b => Math2.Ibetac(a, b, x) - q; } #if EXTRA_DEBUG Debug.WriteLine("IBetaInvB(a={0}, guess?={1}, x={2}) == p({3}), q({4}); range = [{5}, {6}]", a, guess, x, p, q, lower, upper); #endif RootResults r = RootFinder.Toms748Bracket(f, guess, step, FunctionShape.Unknown, lower, upper, _tol, Policies.MaxRootIterations); if (r == null) { Policies.ReportRootNotFoundError("Invalid parameter in root solver"); return(double.NaN); } if (!r.Success) { Policies.ReportRootNotFoundError("Root not found after {0} iterations", r.Iterations); return(double.NaN); } #if EXTRA_DEBUG Debug.WriteLine("Result = {0}; Toms748 iterations: {1}", r.SolutionX, r.Iterations); #endif return(r.SolutionX); }
/// <summary> /// Use the root finder to solve Q(a,x) == q, for x /// </summary> /// <param name="a"></param> /// <param name="q"></param> /// <param name="guess"></param> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static double SolveGivenAQ(double a, double q, double guess, double min, double max) { Func <double, ValueTuple <double, double, double> > halleyF = (double x) => { // Calculate Q(x) - q and the first two derivatives double f = Math2.GammaQ(a, x) - q; double f1 = -Math2.GammaPDerivative(a, x); double f2 = -f1 * (1.0 + (1.0 - a) / x); return(f, f1, f2); }; const double relTolerance = RootFinder.DefaultRelTolerance; const double absTolerance = 0; RootResults rr = RootFinder.Halley(halleyF, guess, min, max, relTolerance, absTolerance, Policies.MaxRootIterations); if (rr == null) { Policies.ReportRootNotFoundError("Invalid parameter in root solver"); return(double.NaN); } #if EXTRA_DEBUG Debug.WriteLine("Halley iterations: {0}", rr.Iterations); #endif if (!rr.Success) { Policies.ReportRootNotFoundError("Root not found after {0} iterations", rr.Iterations); return(double.NaN); } return(rr.SolutionX); }
public void CanFindWhenExistsAndContentIsOk() { Environment.CurrentDirectory = Path.Combine(dir.FullName, "a/b/c/d/e"); RootFinder.ChangeToPathOf("test.info", "teste-teste-teste").Should().Be.True(); Environment.CurrentDirectory.Should().Be(Path.Combine(dir.FullName, @"a\b")); }
public void CanFindWhenNotExists() { Environment.CurrentDirectory = Path.Combine(dir.FullName, "a/b/c/d/e"); RootFinder.ChangeToPathOf("test2.info", "teste-teste-teste").Should().Be.False(); Environment.CurrentDirectory.Should().Be(Path.Combine(dir.FullName, @"a\b\c\d\e")); }
public void GetNthRoot_Test() { double number = double.Parse(TestContext.DataRow["Number"].ToString()); int power = int.Parse(TestContext.DataRow["N"].ToString()); double eps = double.Parse(TestContext.DataRow["Eps"].ToString()); double expected = double.Parse(TestContext.DataRow["Result"].ToString()); double actual = RootFinder.FindNthRoot(number, power, eps); Assert.AreEqual(actual, expected, eps); }
public void Test() { double left = -100; double right = 100; double[] arguments = { 0, 1, -1, 1, -1, 1 }; double result = RootFinder.Solution(left, right, arguments); Assert.AreEqual(0.0, result); }
public void Should_Return0_When_Input0number5degree() { // arrange double number = 0; int degree = 5; double precision = 0.0000001; double expected = 0; // act double actual = RootFinder.Newton(number, degree, precision); // assert Assert.AreEqual(expected, actual); }
public bool TryFactor(out FractionalFunction fractionalFunction) { List <Complex> numRoots = RootFinder.DurandKerner(Num); List <Complex> denRoots = RootFinder.DurandKerner(Den); if (!numRoots.Intersect(denRoots).Any()) { // If factoring is impossible, return this same function fractionalFunction = new FractionalFunction(Num, Den); return(false); } throw new NotImplementedException(); }
public void Bracket_Test() { foreach (TestData d in _FunctionData) { int iterations; RootBracketResult b = RootFinder.FindBracket(d.FuncValue, d.Guess, d.Step, FunctionShape.Unknown, d.Lmin, d.Lmax, RootFinder.DefaultIterations, out iterations); if (b == null) { throw new AssertFailedException(" Bracket Solve: (" + d.Description + ") got null; Tolerance: " + d.RelTolerance); } if (!b.IsValid) { throw new AssertFailedException(" Bracket Solve: (" + d.Description + ") got " + b + " Tolerance: " + d.RelTolerance); } } }
public static void Main() { //Part A Func <vector, vector> f = (z) => { return(new vector(-2.0 * (1 - z[0]) - 400 * (z[1] - Pow(z[0], 2)) * z[0], 200 * (z[1] - Pow(z[0], 2)))); }; vector x = new vector(3, 4); vector result = RootFinder.Newton(f, x); Write("We are finding the minumum of the Rosenbrock's valley function, by Newton's method with numerical Jacobian and back-tracking linesearch"); result.print("The minimum was found to be = "); Write("Which is the exact same as the analytical result."); //Part B StreamWriter outdata = new StreamWriter("out.data", append: false); double rmax = 10; // Defining the function to find root of Func <vector, vector> fe_root = (vector m) => { double e = m[0]; double fe_rmax = hydrogen.find(e, rmax); return(new vector(fe_rmax)); }; // Start condition vector m0 = new vector(-0.5); vector mroots = RootFinder.Newton(fe_root, m0); double e_found = mroots[0]; //collecting data for plotting for (double i = 0; i < rmax; i += 0.1) { outdata.WriteLine("{0} {1} {2}", i, hydrogen.find(e_found, i), i * Exp(-i)); } vector e_found_vec = new vector(e_found); Write(" In part B , the error was found at root = {0}.", fe_root(e_found_vec)[0]); outdata.Close(); //outBtxt.Close(); }
public void DDT_RootFind() { double number = Convert.ToDouble(Convert.ToString(TestContext.DataRow["number"])); int degree = Convert.ToInt32(Convert.ToString(TestContext.DataRow["degree"])); double precision = Convert.ToDouble(Convert.ToString(TestContext.DataRow["precision"])); double expected = Convert.ToDouble(Convert.ToString(TestContext.DataRow["expected"])); if (precision <= 0 || (number < 0 && degree % 2 == 0)) { Assert.ThrowsException <ArgumentOutOfRangeException>(() => RootFinder.FindNthRoot(number, degree, precision)); } else { Assert.AreEqual(expected, RootFinder.FindNthRoot(number, degree, precision), precision); } }
public void BisectionTest() { foreach (TestData d in _FunctionData) { double relTolerance = RootFinder.DefaultRelTolerance; double absTolerance = d.AbsTolerance; // test bisection RootResults results = RootFinder.Bisection(d.FuncValue, d.Min, d.Max, relTolerance, absTolerance, RootFinder.DefaultIterations); double solution = (results == null) ? double.NaN : results.SolutionX; if (!AreNear(solution, d.Expected, relTolerance, absTolerance)) { throw new AssertFailedException(" Bisection Solve: (" + d.Description + ") = " + d.Expected + "; got " + solution + " Tolerance: " + d.RelTolerance); } } }
private void OnDrawGizmos() { FiguresColor(); DrawFunc(Func, From, To); // For method to work as desired, func parameter must have different signs on left and right interval ends BrentsRoot root; if (RootFinder.BrentsMethod(Func, From, To, out root)) { ResultsColor(); DrawPoint(new Vector2(root.X, 0)); LogInfo("Root: " + root.X); } else { LogInfo("No root"); } }
public static (double Result, int Iterations) SolveA(double z, double p, double q, double aGuess, double step, double min, double max) { Debug.Assert(aGuess >= min && aGuess <= max, "Guess out of range"); Func <double, double> f; if (p < q) { f = a => Math2.GammaP(a, z) - p; } else { f = a => Math2.GammaQ(a, z) - q; } // // Use our generic derivative-free root finding procedure. // We could use Newton steps here, taking the PDF of the // Poisson distribution as our derivative, but that's // even worse performance-wise than the generic method :-( // // dQ/da is increasing, dP/da is decreasing FunctionShape fShape = (p < q) ? FunctionShape.Decreasing : FunctionShape.Increasing; RootResults rr = RootFinder.Toms748Bracket(f, aGuess, step, fShape, min, max); if (rr == null) { Policies.ReportRootNotFoundError($"Invalid Parameter: PQInvA(z: {z}, p: {p}, q: {q}) [{min}, {max}] g: {aGuess}"); return(double.NaN, 0); } if (!rr.Success) { Policies.ReportRootNotFoundError("Root not found after {0} iterations", rr.Iterations); return(double.NaN, rr.Iterations); } return(rr.SolutionX, rr.Iterations); }
public void FindRoot_IsCorrect(double number, int power, double accuracy, double expectedResult) => Assert.AreEqual(RootFinder.FindRoot(number, power, accuracy), expectedResult, accuracy);
public void FindRoot_Throws_ArgumentException(double number, int power, double accuracy) => Assert.Throws <ArgumentException>(() => RootFinder.FindRoot(number, power, accuracy));
public double NewtonTest(double number, int root, double acc) { var finder = new RootFinder(); return(finder.NewtonMethod(number, root, acc)); }
public void FindNthRootmethod_UserVariants_CorrectResults(double number, int n, double eps, double result) { Assert.AreEqual(result, RootFinder.FindNthRoot(number, n, eps), 0.1); }
public void FindNthRootmethod_UncorrectData_ArgumentException(double number, int n, double eps) { Assert.Throws <ArgumentException>(() => RootFinder.FindNthRoot(number, n, eps)); }
public void Should_ReturnException_When_InputZeroPrecision() { double precision = 0; RootFinder.Newton(-32, 5, precision); }
public void Should_ReturnException_When_InputNegativePrecision() { double precision = -5; RootFinder.Newton(-32, 5, precision); }
public void Should_ReturnException_When_InputNegativeNumber() { double number = -32; RootFinder.Newton(number, 5, 1); }
public void FindNthRoot_TestsWithValues(double number, int degree, double precision, double result) => Assert.AreEqual(RootFinder.FindNthRoot(number, degree, precision), result, precision);
private void Solve(float[] array, ref string message) { switch (array.Length) { case 2: { float root; if (RootFinder.Linear(array[0], array[1], out root)) { message = "X=" + root; return; } } break; case 3: { QuadraticRoots roots; if (RootFinder.Quadratic(array[0], array[1], array[2], out roots)) { message = "RootCount: " + roots.RootCount + " X0=" + roots.X0 + " X1=" + roots.X1; return; } } break; case 4: { CubicRoots roots; if (RootFinder.Cubic(array[0], array[1], array[2], array[3], out roots)) { message = "RootCount: " + roots.RootCount + " X0=" + roots.X0 + " X1=" + roots.X1 + " X2=" + roots.X2; return; } } break; case 5: { QuarticRoots roots; if (RootFinder.Quartic(array[0], array[1], array[2], array[3], array[4], out roots)) { message = "RootCount: " + roots.RootCount + " X0=" + roots.X0 + " X1=" + roots.X1 + " X2=" + roots.X2 + " X3=" + roots.X3; return; } } break; default: { int degree = array.Length - 1; Polynomial poly = new Polynomial(degree); for (int i = 0; i <= degree; ++i) // Notice i <= degree, as poly of order n has n+1 coeffs { poly[i] = array[i]; } float[] roots; if (RootFinder.Polynomial(poly, out roots)) { message = "RootCount: " + roots.Length; for (int i = 0; i < roots.Length; ++i) { message += " X" + i.ToString() + "=" + roots[i].ToString(); } return; } } break; } message = "Has no solution"; }
public void FindNthRoot_WithNegativeA_ThrowArgumentOutOfRangeException() => Assert.Throws <ArgumentOutOfRangeException>(() => RootFinder.FindNthRoot(-5, -2, 0.001));
public void FindNthRoot_WithIncorrectEpsilon_ThrowArgumentOutOfRangeException() => Assert.Throws <ArgumentOutOfRangeException>(() => RootFinder.FindNthRoot(5, 2, -0.001));