import math


def table2_3():
    #  Solve  f(x) = 0  using the bisection method

    #  Input:
    # a = left endpoint of interval
    # b = right endpoint of interval
    # tol = tolerance for stopping bisection method
    # f(x) at end of file

    a = -2.0
    b = 0.0
    mid = 0.5 * (a + b)
    tol = 10 ** (-6)
    err = 10 * tol

    # bisection procedure
    it = 0
    print("\n RIE = relative iterative error \n")
    print(" k \t\t x_k   \t\t RIE ")
    while err > tol:
        old = mid
        fmid = f(mid)
        if f(a) * fmid < 0:
            b = mid
        elif f(b) * fmid < 0:
            a = mid
        else:
            break
        mid = 0.5 * (a + b)
        it = it + 1
        err = abs((mid - old) / mid)
        print(f" {it:d} \t {mid:19.15f} \t {err:5.1e}")
        # print(f'\\, {it:d} \\, & \\,\\, {mid:19.15f} \\,\\, & \\,\\, {err:5.1e}  \\\\\\hline')
    print()


def f(x):
    # g=x^3-3*x+1;
    g = math.exp(-x) - (2 + x)
    return g


if __name__ == "__main__":
    table2_3()
