#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 16:16:15 2024

@author: sam
"""

import numpy as np

roots = []

'''define functions'''
def f(x):
    return np.exp(x) - 3*x**2

def bracket(f,a,b,N):
    x = np.linspace(a,b,N)
    for i in range(len(x)-1):
        if f(x[i])*f(x[i+1])<0:
            roots.append([x[i],x[i+1]])

def falseposition(f,a,b,tol):
    while abs(b-a) >= tol:
        c = (b*f(a)-a*f(b))/(f(a)-f(b))
      
        if f(a)*f(c)<0:    #check if n,p bracket the root
            b = a
            a = c
        elif f(b)*f(c)<0:  #check if m,p bracket the root
            b = a
            a = c
        '''
        if f(a)*f(c) > 0:
            a = c
        elif f(c)*f(b) > 0:
            b = c
        else:
            print('Fail')
            break
        #old method
        '''
    return c



bracket(f,-2,2,20)

for i in range(len(roots)):
    [a,b] = roots[i][:]
    print(falseposition(f,a,b,1e-4))