Skip to content

Instantly share code, notes, and snippets.

@LeonardoWlopes
Created April 13, 2024 16:22
Show Gist options
  • Save LeonardoWlopes/f813dd645918fc9b45f142d475102bb0 to your computer and use it in GitHub Desktop.
Save LeonardoWlopes/f813dd645918fc9b45f142d475102bb0 to your computer and use it in GitHub Desktop.
codigos da thais
from decimal import *
def horner(p, x):
res = p[-1] # isto é o valor a_n
for i in range(len(p)-2, -1, -1):
res = res * x + p[i]
return res
def find_root(p, a, b, tolerance=Decimal('1e-10')):
if horner(p, a) * horner(p, b) > 0:
print("Não é possível garantir que há uma raiz no intervalo fornecido.")
return None
while abs(b - a) > tolerance:
midpoint = (a + b) / Decimal('2')
if horner(p, midpoint) == 0:
return midpoint
elif horner(p, a) * horner(p, midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / Decimal('2')
# Configurando a precisão decimal
getcontext().prec = 3
# Coeficientes do polinômio
p = [Decimal('1'), Decimal('-5.21287'), Decimal('-7.66759'), Decimal('33.35757')]
# Encontrando uma raiz do polinômio p(x) = 0 no intervalo [0, 1]
raiz = find_root(p, Decimal('0'), Decimal('1'))
print(f'Uma raiz de p(x) = 0 no intervalo [0, 1] é aproximadamente {raiz}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment