import math
import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler


def fig2_11():
    #  Solve  F(x,y) = 0  using Newton's method

    #  Input:
    # xa = starting point
    # tol = tolerance for stopping
    # f(x) and df(x) are at end of file

    a = 0
    b = 8
    nx = 20
    x = np.linspace(a, b, nx)

    tol = 10 ** (-8)

    y = np.zeros(nx)
    y[0] = 0
    for ix in range(nx):
        err = 10 * tol
        while err > tol:
            z = f(x[ix], y[ix]) / df(x[ix], y[ix])
            y[ix] = y[ix] - z
            err = abs(z / y[ix])
            # print(f' {it:d} & {x:19.15f} & {err:5.1e} \\\\\\hline')
        if ix < nx - 1:
            y[ix + 1] = y[ix]

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(
        figsize=(658 / 100, 230 / 100), dpi=100, constrained_layout=True
    )
    # subaxis(1,1,1,1,'MT',0.01,'MB',0.18,'MR',-0.02,'ML',0.03,'P',0.04)
    co = [
        (0, 0, 1),
        (0, 0.5, 0),
        (1, 0, 0),
        (0, 0.75, 0.75),
        (0.75, 0, 0.75),
        (0.75, 0.75, 0),
        (0.25, 0.25, 0.25),
    ]
    plt.rcParams["axes.prop_cycle"] = cycler(color=co)

    ax.plot(x, y, "--b", linewidth=1)
    ax.plot(x, y, "ob", markersize=8, linewidth=1)
    for spine in ax.spines.values():
        spine.set_visible(True)
    ax.grid(True)
    ax.axis([a, b, -3, 0])
    ax.set_xlabel("x-axis")
    ax.set_ylabel("y-axis")
    ax.tick_params(labelsize=14)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight("bold")
    ax.xaxis.label.set_fontsize(14)
    ax.yaxis.label.set_fontsize(14)
    ax.xaxis.label.set_fontweight("bold")
    ax.yaxis.label.set_fontweight("bold")

    # fig.savefig('/Users/mark/Desktop/implicit.eps')
    plt.show()


def f(x, y):
    g = y + x + 2 - math.exp(math.sin(x) - y)
    return g


def df(x, y):
    g = 1 + math.exp(math.sin(x) - y)
    return g


if __name__ == "__main__":
    fig2_11()
