# -*- coding: utf-8 -*-
"""
Created on Sat Aug  6 14:52:12 2022

@author: Chris
Lab 2 Q4
"""

import numpy as np
import matplotlib.pyplot as plt

def myfun(x):
    myfun = x**4-x-1
    return myfun

def bracket(f,a,b,N):
    # function that attempts to bracket a 
    # zero of a function f between a and b
    #
    # returns a list of brackets for each zero crossing of f.
    
    blist = []
    x = np.linspace(a,b,N)
    
    for i in range(1,len(x)): #loop over all the points
        if f(x[i])*f(x[i-1])<0: # check if there's a crossing
            blist.append([x[i-1],x[i]]) # append if so
            
    return blist
    
def secant(f,a,b,tol):
    # function that applies the secant method to find
    # a zero of f to within a tolerance of tol 
    # given the initial interval [a,b]
    
    NMAX = 1000
    
    xn = a
    xm = b
    
    N = 1
    while N<NMAX:
        
        print(N,xn,xm)
        
        fn = f(xn)
        fm = f(xm)
        
        xp = (xm*fn-xn*fm)/(fn-fm)
        
        xm = xn
        xn = xp
        
        if abs(xn-xm)<tol:
            return xn
        
        N = N + 1
        #end of while loop
    
    print("Secant warning: Maximum iterations exceeded.")
    return xp

"""Main script starts"""

x = np.linspace(-2,2,100)
plt.plot(x,myfun(x))

blist = bracket(myfun,-2,2,20)
    
for i in range(0,len(blist)):
        [a,b] = blist[i][:]
        x0 = secant(myfun,a,b,1e-4)
        print("Zero found at:",x0)
        
        
        
    
    

    
