Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert float to integer in prolog

How to convert float to integer in prolog?

I tried:

?- integer(truncate(sqrt(9))).
false.

?- integer(round(sqrt(9))).
false.
like image 618
Martynas Avatar asked Dec 04 '10 16:12

Martynas


1 Answers

The predicate integer/1 that you used is true iff its argument is an integer. Since the term truncate(sqrt(9)) is not an integer, the predicate does not hold and therefore fails for this term.

There are at least two ways to get what you want:

Solution 1: Quick and broken

You can use the predicate (is)/2 for conversion between different number representations. In particular, check out the arithmetic functions round, truncate and ceiling. For example:

?- X is round(sqrt(9)).
X = 3.

However, note that using floating point numbers is always highly problematic. For example:

?- X is sqrt(2^10000).
ERROR: is/2: Arithmetic: evaluation error: `float_overflow'

There are also other issues such as rounding errors and possible underflow.

Solution 2: Quick and general

Due to the inherent shortcomings of floating point numbers, I strongly recommend you use more general mechanisms instead. For example several Prolog systems support rational numbers and integers with unbounded precision, whereas floats are always limited to machine precision.

If you need integer square roots, use for example finite domain constraints. With constraints, it suffices to state what holds for an integer X that denotes the positive square root:

?- X*X #= 9, X #>= 0.
X = 3.

This also works for larger integers:

?- X*X #= 2^10000, X #>= 0.
X = 1412467032...(1496 digits omitted)

See clpfd for more information.

like image 140
mat Avatar answered Sep 27 '22 17:09

mat