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

from plot_helpers import CO, bold_ticks


def fig7_14():
    # comparison of imaginary and centered difference approximations for f'(x)

    x0 = 1
    exact = 0.5

    h = np.zeros(16)
    cd = np.zeros(16)
    c = np.zeros(16)
    errc = np.zeros(16)
    errcd = np.zeros(16)

    for k in range(16):
        h[k] = 1 / 10 ** k
        cd[k] = np.imag(f(x0 + 1j * h[k])) / h[k]
        c[k] = (f(x0 + h[k]) - f(x0 - h[k])) / (2 * h[k])
        errc[k] = abs(exact - c[k])
        errcd[k] = abs(exact - cd[k])

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(8.8, 3.3))
    fig.subplots_adjust(left=0.10, right=0.98, bottom=0.22, top=0.98)
    ax.set_prop_cycle(cycler(color=CO))

    ax.loglog(h, errc, "bo--", markersize=8, linewidth=1.4)
    ax.loglog(h, errcd, "r*-", markersize=8, linewidth=1.4)
    ax.legend(
        [" Centered", " CTSE"],
        loc="lower left",
        prop={"size": 12, "weight": "bold"},
    )
    ax.grid(True)
    ax.set_xlabel("Stepsize (k)")
    ax.set_ylabel("Error")
    bold_ticks(ax, 14)
    plt.show()

    # plt.savefig('/Users/mark/Desktop/ctse.eps')


def f(x):
    y = np.sqrt(x)
    return y


if __name__ == "__main__":
    fig7_14()
