Zeros of a function with bisection method and automatic intervals finder

101 Views Asked by At

i was trying to find the zeros of my function but i don'know how to make my program find automatically the intervals where there is a zero of the function. I found the intervals manually and visually but this not the request of the exercise. Can someone help me? it's pretty important. this is the code that i wrote ( i can only use matplolib.pyplot and numpy):

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x**2-13*x-4)-np.cos(2*x**2-23*x-4)

x=np.arange(4,8,0.0001)

plt.plot(x,f(x),'r',x,x*0,'b')
plt.title('Grafico della funzione')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.show()

def bisection(f, a, b, tol=1e-9):
    
    if f(a) * f(b) >= 0:
        return None
    
    
    iter = 0
    while b - a > tol:
       
        c = (a + b) / 2
        fc = f(c)
        
        
        if fc == 0:            
            return c 
        elif f(a) * fc < 0:
            b = c  
        else:
            a = c  
        iter += 1
    
    
    return (a + b) / 2, iter

intervals=[(4, 4.5), (4.5, 6), (7, 7.2), (7.2, 7.3), (7.7, 8)]

roots=[]

for a,b in intervals:
    root=bisection(f,a,b,tol=1e-7)
    roots.append(root)
print(roots)
1

There are 1 best solutions below

0
guidot On

Concentrating on the algorithm: A workable solution is Newton's method: You start at an arbitrary (=guessed) x, and compute, where the slope of the tangent intersects the x axis. As soon as as between x-d and x+d the sign of the function changes, you have your boundary values. Repeat that with different start values until you think to have all zeors - and no, the algorithm will be of no help to decide, whether you are finished.