netotz
netotz

Reputation: 332

PROLOG - How to round decimals of floating point numbers?

I have this line in the knowledge base:

height(Hipot,Y) :- Y is sin(pi/6)*Hipot.

which calculates one of the cathetus of a right triangle.

When asking Prolog for the value of Y, that is the cathetus, I get an inaccurate number:

?- height(1,Y).
Y = 0.49999999999999994.

But the real value is 1/2, so it should output 0.5. I guess that the inaccuracy is because of the use of pi, but I want to keep using it so how can I round Y to 0.5?

Upvotes: 2

Views: 4082

Answers (3)

user3170496
user3170496

Reputation:

By using format/3 you can output to an argument:

format(atom(A), '~2f', [Y]), writeln(A).

Upvotes: 0

mat
mat

Reputation: 40768

One straight-forward solution is to use format/2 to output the number with a given "precision". For example:

?- height(1,Y), format("~2f", [Y]).
0.50
Y = 0.49999999999999994.

Note that floats will consistently lead to such issues, and wherever possible, I recommend to use for example rational numbers instead.

Upvotes: 6

Neal Fultz
Neal Fultz

Reputation: 9687

I am trying to learn prolog as well. The built-in round function only goes to the nearest integer, so I defined a rule that extends it to round to a certain number of digits:

round(X,Y,D) :- Z is X * 10^D, round(Z, ZA), Y is ZA / 10^D

I'm not sure if it's idiomatic, but it seems to work:

?- round(5.5555, Y, 2).
Y = 5.56.

Upvotes: 4

Related Questions