Actually, it is easy to define a predicate truncate/3 in Prolog. Let's say that we want truncate a real number X up to N decimal places and store its result in Result. Using the mathematical function for truncation in this Wikipedia site, we can define the predicate as follows:
% truncation for positive numbers
truncate(X,N,Result):- X >= 0, Result is floor(10^N*X)/10^N, !.
% truncation for negative numbers
truncate(X,N,Result):- X <0, Result is ceil(10^N*X)/10^N, !.
I use cut because the two above cases are mutually exclusive.
Actually, it is easy to define a predicate
truncate/3
in Prolog. Let's say that we want truncate a real numberX
up toN
decimal places and store its result inResult
. Using the mathematical function for truncation in this Wikipedia site, we can define the predicate as follows:I use cut because the two above cases are mutually exclusive.