本文介绍了Prolog中的二次方程求解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个代码来求解具有相似项的方程(例如:- x^2+5*x+6=0).这里 'x' 有两个值.我可以通过输入';'来取两个值.但是当我一次运行程序时,我需要得到所有可能的答案.在序言中可以吗?

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?

推荐答案

对于二次方程,如果判别式为零,则只有一个解,所以你可以直接计算一两个解决方案,并在列表中返回它们.

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

判别式是平方根下的表达式.所以实数解的经典序言代码如下:

The discriminat is the expression under the square root. So theclassical 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]).

这是一个示例运行:

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].

这篇关于Prolog中的二次方程求解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 17:23