def test_tan_x(): """ Example also taken from literature/NewtonRaphson.pdf """ assert tan_func(0.5) == approx(-0.04630248) value = newton_raphson(4.6, 1e-6, root=tan_func) assert value == approx(4.49341)
def test_basic_sanity(): """ Pedagogical example from S. Gourley's notes at University of Surrey. In this repo see `literature/NewtonRaphson.pdf` Online: http://personal.maths.surrey.ac.uk/st/S.Gourley/NewtonRaphson.pdf Solves x^3 - x - 1, starting at x0=1.0 to 5d.p. """ no_kwargs = newton_raphson(1, 1e-6) assert no_kwargs == 0.0 assert func(0.5) == approx(-1.375) value = nr_func(1, 1e-6) assert value == approx(1.324717) assert newton_raphson(1, 1e-6) == 0.0 assert func(0.5) == approx(-1.375)
def test_with_local_function(): """ Example also taken from literature/NewtonRaphson.pdf """ def cos_func(x): return cos(x) - 2 * x assert cos_func(0.5) == approx(-0.12241743) value = newton_raphson(0.5, 1e-6, root=cos_func) assert value == approx(0.4501836) assert cos_func(0.5) == approx(-0.12241743)
from numpy import cos from pytest import approx from fastats.optimise.newton_raphson import newton_raphson def func(x): return x**3 - x - 1 def less_or_equal(x, compared_to, rel=1e-6): return ((x < compared_to) or ((x - compared_to) == approx(0.0, rel=rel)) or (x == approx(x, rel=rel))) nr_func = newton_raphson(1, 1e-6, root=func, return_callable=True) @given(floats(min_value=0.01, max_value=3.5)) def test_minimal(x): """ Tests that the value output from the solver is less than or equal to the value of the objective. """ eps = 1e-12 value = nr_func(x, eps) assume(func(x) > 0.0) assert less_or_equal(value, compared_to=func(x))
def test_non_converging(): """ Example also taken from literature/NewtonRaphson.pdf """ with raises(ZeroDivisionError): # Runtime Warning in Python _ = newton_raphson(5.0, 1e-6, root=tan_func)
from hypothesis import given from hypothesis.strategies import floats from numpy import cos, tan from pytest import approx, raises from fastats.optimise.newton_raphson import (newton_raphson, root) def func(x): return x**3 - x - 1 nr_func = newton_raphson(1, 1e-6, root=func, return_callable=True) def test_basic_sanity(): """ Pedagogical example from S. Gourley's notes at University of Surrey. In this repo see `literature/NewtonRaphson.pdf` Online: http://personal.maths.surrey.ac.uk/st/S.Gourley/NewtonRaphson.pdf Solves x^3 - x - 1, starting at x0=1.0 to 5d.p. """ no_kwargs = newton_raphson(1, 1e-6) assert no_kwargs == 0.0 assert func(0.5) == approx(-1.375) value = nr_func(1, 1e-6) assert value == approx(1.324717)