#!/usr/bin/env python3

import matplotlib.pyplot as plt
import numpy as np
from math import *
import readline
import sys
import os
fhist = os.path.join(os.path.expanduser("~"), ".history.math")
if not os.path.exists(fhist):
    readline.write_history_file(fhist)
readline.read_history_file(fhist)

N = 1000
W = 100
d = 0.9

while True:
    try:
        f = np.vectorize(eval(f"lambda x: {input('f(x): ')}"))
        XX = np.linspace(-W, W, W**2)
        XX = XX[np.abs(f(XX)) < d]
    except (EOFError, KeyboardInterrupt):
        break
    except Exception as E:
        print(f"Error {E}")
        continue
    if XX.size < 2:
        print("No roots")
        continue
    a, b = XX.min(), XX.max()

    #a, b = eval(input("a, b: "))
    A, B = 0, 0
    while (A, B) != (a, b):
        A, B = a, b
        X = np.linspace(A, B, N)
        Y = f(X)
        fig, ax = plt.subplots()
        ax.plot(X, Y)
        ax.grid()
        if X.min()<=0 and X.max()>=0:
            ax.plot([0,0], ax.get_ylim())
        ax.plot(ax.get_xlim(), [0,0])
        A, B = ax.get_xlim()
        plt.show()
        a, b = ax.get_xlim()
        print(f"{A}, {B}")

readline.write_history_file(fhist)
