1

How to truncate a floating point number up to N decimal places in Prolog?

Is there any built-in tool for this?

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
Deeps
  • 13
  • 2

1 Answers1

1

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.

Iqazra
  • 419
  • 1
  • 3
  • 11
  • Thanks for the answer! But I was wondering why there is no inbuilt predicate for such simple thing. Although format/2 predicate works but I later realised that using format/2, we cannot save the output in any variable, the output will go straight to the stream. – Deeps Apr 26 '18 at 11:39
  • Because initially Prolog was not intended for numerical computation. It may seem simple in procedural language, but in Prolog we have to adapt with declarative (in particular logic) programming paradigm. – Iqazra Apr 26 '18 at 11:49
  • You should always cut as soon as possible, here immediately after the `X>=0` test. The cut in the last clause is unnecessary.You can also simplify your code by using the built-in `truncate` function instead of `floor` and `ceil`. – jschimpf Apr 26 '18 at 21:33