Why is sqrt/2 semidet?

Given:

?- X is 4^2.
X = 16.

?- X is -4^2.
X = 16.

?- X is sqrt(16).
X = 4.0.

Why not:

?- X is sqrt(16).
X = 4.0 ;
X = -4.0.

?

I’d expect a function to return a single answer, but we’re in Prolog so we can backtrack and return both? Perhaps this’d make more sense as:

?- sqrt(16, X).
X = 4.0 ;
X = -4.0.

Which we could define as:

sqrt(A, B) :-
    % Leave Error check for instantiated A to is/2
    C is sqrt(A), % positive result
    ( B = C
    ; B is 0-C
    ).
1 Like

C, Python, etc. define sqrt as the positive square root.
If you think that numerical functions are the same as mathematics functions, you’re going to find yourself in a world of pain (I vividly remember the numerical analysis course I took, with all the error analysis stuff).

But your predicate sqrt/2 is fine if you want both positive and negative results. :wink:

2 Likes

Right?! So why don’t we have an appropriate sqrt/2 predicate in the standard library? The one we have is listed as being for Quintus compatibility and acts like the function, but it’d be nice to have a truthful one.

logical arithmetic is the domain of constraints. The closest I can get is this (clpqr doesn’t seem to know about sqrt/1. I might have missed something though as I never used these libraries).

?- use_module(library(clpr)).
?- { A^2 =:= 4 }.
A = 2.0 ;
A = -2.0 ;
3 Likes

Awesome, so I was just looking in the wrong place!