Skip to content

Instantly share code, notes, and snippets.

@robintux
Created October 31, 2025 14:29
Show Gist options
  • Select an option

  • Save robintux/e1f55d06ed05b9e2db2c5e96f8fa6d2d to your computer and use it in GitHub Desktop.

Select an option

Save robintux/e1f55d06ed05b9e2db2c5e96f8fa6d2d to your computer and use it in GitHub Desktop.
def bisection(f,a,b,N):
'''Aproximacion de la solucion para f(x)=0 en el intervalo [a,b]
por el metodo de Biseccion
https://en.wikipedia.org/wiki/Bisection_method
Parametros de entrada
----------
f : function
La función para la cual estamos tratando de aproximar una solución f(x)=0.
a,b : numeros reales
El intervalo [a,b] es donde se busca la solucion. La funcion retorna
None si f(a)*f(b) >= 0 pues a solucion no esta garantizada
N : Entero positivo
NUmero de iteraciones.
Salida
-------
x_N : Numero real
Este es el punto medio del n-esimo intervalo calculado por el metodo
de la biseccion. El intervalo inicial [a_0,b_0] esta dado por [a,b]
Si f(m_n)==0 para algun punto medio m_n = (a_n + b_n)/2 entonces la funcion
retorna la solucion .
Si los signos de f(a_n), f(b_n) y f(m_n) son iguales en alguna iteracion,
entonces el metodo de biseccion falla .
Ejemplos
--------
>>> f = lambda x: x**2 - x - 1
>>> bisection(f,1,2,25)
1.618033990263939
>>> f = lambda x: (2*x - 1)*(x - 3)
>>> bisection(f,0,1,10)
0.5
'''
if f(a)*f(b) >= 0:
print("El metodo de la biseccion falla.")
print("El intervo [a,b] no es el adecuado")
return None
a_n = a
b_n = b
for n in range(1,N+1):
m_n = (a_n + b_n)/2
f_m_n = f(m_n)
if f(a_n)*f_m_n < 0:
a_n = a_n
b_n = m_n
elif f(b_n)*f_m_n < 0:
a_n = m_n
b_n = b_n
elif f_m_n == 0:
print("Solucion Exacta.")
return m_n
else:
print("El metodo de la biseccion falla.")
return None
return (a_n + b_n)/2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment