I tried to solve the problem of a point belongs to the area. As a result, I need to get an answer: if a point belongs to the area or not.
Coordinates of the point entered by the user from the keyboard. When I try to transfer the coordinates of the point directly in a rule: belongsTo (1,1).
I get the desired result (yes or no), but when I enter the coordinates with the keyboard
write ("Input X:"), readreal (X),
write ("Input Y:"), readreal (Y),
belongsTo (X, Y).
Then the answer will be 'no solutions' or just '2 solutions' (X = 0, Y = 0, X = 0, Y = 0, if you pass the point (0,0))
Here's the code completely:
PREDICATES
square(real,real)
semicircle(real,real)
belongsTo(real,real)
CLAUSES
square(X,Y):-
X>=-1,X<=0,
Y>=-1,Y<=0.
semicircle(X,Y):-
X>=0,Y>=0,
X*X+Y*Y<=1.
belongsTo(X,Y):-
square(X,Y);
semicircle(X,Y),!.
GOAL
write("Input X: "), readreal(X),
write("Input Y: "), readreal(Y),
belongsTo(X,Y).
As a result I need to get a solution like YES(if the point belongs to the area) or NO.
When you use the prompting method:
write("Input X:"), readreal(X),
write("Input Y:"), readreal(Y),
belongsTo(X, Y).
Prolog will display the values of X
and Y
along with the solution (yes or no) because these variables appear explicitly in your query. Any variables in your query it assumes you want to see the results of. If you just want to see yes or no, then you can make a predicate:
readuser :-
write("Input X:"), readreal(X),
write("Input Y:"), readreal(Y),
belongsTo(X, Y).
And then just query readuser
. You'll then just get yes or no without the values of X
and Y
displayed.
As far as the different results, if you enter 0
and 0
for X
and Y
, this input will succeed twice: once for semicircle
and once for square
. Prolog faithfully finds both successful results.
When you are entering 1 and 1 and reading them as "real", I am suspecting that the internal representation is getting a little bit of floating point accuracy issue and internally becoming something like, 1.000000001
and these will fail both the semicircle
and square
tests.
As an aside, the semicircle
is testing for the non-negative X
and non-negative Y
quadrant, not really a semicircle. Actual semicircle
checks would be constraining just one of the coordinates in conjunction with X*X + Y*Y <= 1
, e.g., X >= 0, X*X + Y*Y <= 1
would be the upper right and lower right quadrants of the semicircle.