Pergunta

How I can implement in Prolog program that find coefficients of the polynomial if I know its roots.

for example:

input data (2;-1)
output (1;-1;2)
Foi útil?

Solução

Multiplying together the first-degree factors for given roots will form an expanded polynomial. This is a natural fit with an "accumulator" design pattern in Prolog.

That is, we'll introduce an auxiliary argument to remember the product of factors "so far" dealt with. Once the list of specified roots has been emptied, then we will have the desired polynomial expansion:

/* polynomialFromListofRoots(ListofRoots,[1],Polynomial) */
polynomialFromListofRoots([ ],Poly,Poly).
polynomialFromListofRoots([R|Roots],Pnow,Poly) :-
    polyMultiplyRootFactor(R,Pnow,Pnew),
    polynomialFromListofRoots(Roots,Pnew,Poly).

/* polyMultiplyRootFactor(R,Poly,ProductXminusR) */
polyMultiplyRootFactor(R,Poly,Prod) :-
    polyMultiplyRootFactorAux(R,0,Poly,Prod).

/* polyMultiplyRootFactorAux(R,Aux,Poly,Product) */
polyMultiplyRootFactorAux(R,A,[ ],[B]) :-
    B is -R*A.
polyMultiplyRootFactorAux(R,A,[P|Ps],[RP|RPs]) :-
    RP is P - R*A,
    polyMultiplyRootFactorAux(R,P,Ps,RPs).

Using the example in the Question:

?- polynomialFromListofRoots([2,-1],[1],Poly).

Poly = [1, -1, -2]
yes

Note that this corrects the output claimed in the Question.

Outras dicas

Sorry misread question.

a^2x + bx +c = 0

Take the sum of the roots x1 + x2 this is equal to -b/a.

Take the product of the roots x1*x2 this is equal to c/a.

Now solve the resulting system of linear equations to find a b and c.

Edit:

The above solution works if you set the parameter of a = 1. You see when your given the roots you'll end up with two equations and three unknowns so you'll have to set a fixed value on one of the parameters and the above solutions fixes a = 1.

So given 2 roots you can't get back a specific polynomial because theres no unique answer theres an infinte number of answers

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top