Quadratic equation solving in Prolog

2019-06-22 09:36发布

I have wrote a code to solve equation with like terms (eg:- x^2+5*x+6=0). Here 'x' has two values. I can take two values by entering ';'. But I need to get the all possible answers when I run the program at once. Is it possible in prolog?

标签: prolog
1条回答
欢心
2楼-- · 2019-06-22 10:26

Well for a quadratic equation, if the discriminant is zero, then there is only one solution, so you can directly compute one or two solutions, and return them in a list.

enter image description here

The discriminat is the expression under the square root. So the classical prolog code for a real number solution reads as follows:

solve(A*_^2+B*_+C=0,L) :- D is B^2-4*A*C,
   (D < 0 -> L = [];
    D =:= 0 -> X is (-B)/(2*A), L = [X];
    S is sqrt(D), X1 is (-B-S)/(2*A), 
      X2 is (-B+S)/(2*A), L=[X1,X2]).

Here is an example run:

Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.0)

?- solve(1*x^2+5*x+6=0,L).
L = [-3.0, -2.0].
查看更多
登录 后发表回答