def plot_convergence():
    """Compare convergence of various methods.

    Methods: Newton's method, Broyden's method, and function iteration.

    References
    ----------
    .. [RA20] Randall Romero-Aguilar. A Python version of Miranda and Fackler’s
    CompEcon toolbox. 2020. URL: https://github.com/randall-romero/CompEcon.
    """
    def f(x):
        fval = np.exp(x) - 1
        x_values.append(x)
        return fval

    def f_2(x):
        fval = np.exp(x) - 1
        x_values.append(x)
        return fval, np.exp(x)

    get_log_error = lambda z: np.log10(np.abs(z)).flatten()  # noqa

    # Newton
    x_values = []
    _ = newton_method(f_2, 2)
    error_newton = get_log_error(x_values)

    # Broyden
    x_values = []
    _ = root(f,
             2.0,
             method="broyden1",
             options={"jac_options": {
                 "alpha": -1 / np.exp(2)
             }})
    error_broyden = get_log_error(x_values)

    # Function iteration
    x_values = []
    _ = funcit(f, x0=2)

    error_funcit = get_log_error(x_values)

    # Plot results.
    plt.figure(figsize=[10, 6])
    plt.plot(error_newton, label="Newton's Method")
    plt.plot(error_broyden, label="Broyden's Method")
    plt.plot(error_funcit, label="Function Iteration")
    plt.title(r"Convergence rates for $f(x)= exp(x)-1$ with $x_0=2$")
    plt.xlabel("Iteration")
    plt.ylabel("Log10 Error")
    plt.xlim(0, 10)
    plt.ylim(-5, 2)
    plt.legend()
Esempio n. 2
0
def test_3():
    """Newton method is working."""
    def _jacobian(x):
        return 3 * x**2

    def _value(x):
        return x**3 - 2

    def f(x):
        return _value(x), _jacobian(x)

    x = newton_method(f, 0.4)
    np.testing.assert_almost_equal(f(x)[0], 0)
def test_exercise_4():
    """Test for exercise 4."""
    for x0 in [-0.01, 0.01]:
        x = newton_method(newton_pathological_example, 0.45)
        print(f"candidate for root {x[0][0]:+5.3f}")