Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving a system of equations in Prolog

Assume I have a number X and I wish to solve system of equations, say Y+Z=X, Z*Y = 1.

Now, this has solutions Y=1/Z and Z = (sqrt(X*X-4)+X)/2 or (X-(sqrt(X*X-4)))/2.

So I can write in Prolog:

solve(X,Y,Z):- Y is (sqrt(X*X-4)+X)/2, Z is 1/Y.
solve(X,Y,Z):- Y is (X-(sqrt(X*X-4)))/2,Z is 1/Y.

This works.

BUT

it requires a lot of preliminary work from my part, essentially solving it beforehand and just asking Prolog to evaluate the answer.

Is there some way I can get Z and Y, without solving X beforehand?

I cannot just write stuff like

solve(X,Y,Z):- X is Y+Z, Z is 1/Y.

because of instantiation error.

like image 865
Valtteri Avatar asked Apr 12 '13 17:04

Valtteri


1 Answers

I think that you would need a CAS, to symbolically solve the system, as you did "by hand". Such SW is neither easy to find nor to build.

If a pragmatic approach can do it for you, library(clprq) could help:

:- [library(clpr)].
solve(X,Y,Z) :- {Y+Z=X, Z*Y=1}.

yields

?- solve(3,Y,Z).
{Z=3.0-Y, -1.0+Z*Y=0.0},
{-1.0+Z*Y=0.0},
{-1.0+Z*Y=0.0}.

does this make sense?

like image 131
CapelliC Avatar answered Nov 14 '22 23:11

CapelliC