I’m not getting through two lists, can anyone help me?

Asked

Viewed 59 times

-2

What I want is to find the roots of a polynomial. With this, I created a list with the coefficients of the polynomial and another list with the candidates to be roots. I need to test all of them and find the roots. But it’s not working.

Taking a polynomial for example: x² - 5x + 6

p = [6, -5, 1] #coef. do polinômio
candidatos = [-1, 1, -2, 2, -3, +3, -6, +6]

r = [] 

resultado = 0

i = 0

while i < len(candidatos) + 1:

    for coef in p:

        resultado = resultado * k[a] + coef   #Briot Ruffini

        if resultado == 0:
            r.append(k[a])

    i = i + 1

print(r)

2 answers

0

Who would be k and who would be a in your code ?

I made a little code, I hope it helps, I didn’t use a Briot-Rufinni algorithm, I put 1/3 and 1/2, which are the roots of this polynomial to do a test. Use the Math library to calculate power.

from math import pow

p = [6, -5, 1] #coef. do polinômio
candidatos = [-1, 1, -2, 2, -3, +3, -6, +6, 1/3, 1/2]

r = list()
exponte = len(p) - 1 #pega o tamanho de p, no caso 3 e tira 1, obetendo o grau do polinomio

for i in candidatos:  #testa cada um dos candidatos
    resultado = 0 #armazenar o resultado

    for j in p: #intera dentro do polimonio com o canditato
        resultado += j*pow(i, exponte) #com o exponte você faz 6*(i)^2 e vai somando
        exponte -= 1 #na segunda interação o expoente que era 2 passa a ser 1

    if resultado == 0: #se o resultado for 0 entra nesse if
        r.append(i)

    resultado = 0 #zera o resultado para repetir o processo

print(r)
  • in place of k[a] consider candidates[i]

  • Interesting your code, but I can’t use the Math library but I appreciate the help!

0

I broke my head a little bit and implemented this briot-rufini

p = [6, -5, 1] #coef. do polinômio
candidatos = [1, -2, 2, -3, +3, -6, +6, 1/3, 1/2]

raiz = list()
aux = 0

for i in candidatos:
    for j in p:
        r = j + aux
        aux = r*i
    if r == 0:
        raiz.append(i)

    r = 0
    aux = 0

print(raiz)
  • Thank you very much, it was very simple to understand!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.