You are on page 1of 1

import numpy as np

import matplotlib.pylab as plt

def metoda_bisectiei(a,b,f,epsilon):
x_num = (a+b)/2.
N = int(np.floor(np.log2((b-a)/epsilon)))
for _ in range(1,N):
if f(x_num) == 0:
break
elif np.sign(f(a)) * np.sign(f(x_num))<0:
b = x_num
else:
a = x_num
x_num = (a+b)/2.
return x_num,N

def desenare_grafic(interval,functions,points):
plt.figure(0)
domain = np.linspace(start=interval[0],stop=interval[1])
for element in functions:
values = element[0](domain)
legend_label = element[1]
plt.plot(domain,values,label=legend_label)
if points is not None:
for point in points:
plt.scatter(point[0],0,label=point[1])
plt.axhline(0,c='black')
plt.axvline(0,c='black')
plt.xlabel('points')
plt.ylabel('values')
plt.title('Metoda Bisectiei')
plt.grid()
plt.legend()
plt.show()

def functie(x):
return -x ** 3 - 2 * np.cos(x)

def bisectie():
a = -3
b = 3
N = 1000
epsilon = 1e-1
x_num,steps = metoda_bisectiei(a=a,b=b,f=functie,epsilon=epsilon)
desenare_grafic(
interval=[-3,3],
functions=[(functie,'f(x)')],
points=[(x_num,'x_aprox')]
)
print(f'Solutia ecuatiei f(x)=0 are solutia aproximata {x_num:.8} gasita
dupa {steps} pasi')

bisectie()

You might also like