[comp.lang.prolog] HELP!! Need a square root function/predicate in Prolog

sanjiv@fergvax.unl.edu (Sanjiv K. Bhatia) (08/08/90)

Hi there:

I am working on some experiments using Prolog and need a square root function.
Will some kind soul mail me a copy of the same if you happen to have one handy?

Thanks in advance.

Sanjiv
Sanjiv K. Bhatia				Department of Computer Science
sanjiv@fergvax.unl.edu				Ferguson Hall 115
voice: (402)-472-3485				University of Nebraska - Lincoln
fax  : (402)-472-7767				Lincoln, NE 68588-0115

vu0310@bingvaxu.cc.binghamton.edu (R. Kym Horsell) (08/08/90)

In article <1990Aug08.001233.6587@hoss.unl.edu> sanjiv@fergvax.unl.edu (Sanjiv K. Bhatia) writes:
>Hi there:
>
>I am working on some experiments using Prolog and need a square root function.
>Will some kind soul mail me a copy of the same if you happen to have one handy?

A suitable routine might use the Newton-Raphson method as follows
(assuming all appropriate floating-point convensions):

sqrt(X,X) :- X>=0, X=<1, !.
sqrt(X,Y) :- X>1, X2 is X/2, eps(EPS), nr(EPS,X,X,X2,Y).

nr(EPS,X,G1,G2,Y) :- abs(G1-G2,T), T<EPS, !, Y is (G1+G2)/2.
nr(EPS,X,G1,G2,Y) :- G is 0.5*(G2+X/G2), nr(EPS,X,G2,G,Y).

abs(X,X) :- X>=0, !.
abs(X,Y) :- X<0, Y is -X.

eps(1.0e-6).

-Kym
===

steve@comp.vuw.ac.nz (Steve Cassidy) (08/09/90)

Sanjiv K. Bhatia writes:
>I am working on some experiments using Prolog and need a square root
>function. Will some kind soul mail me a copy of the same if you happen to
>have one handy? 


It's probably nothing like what you wanted but here's a version
of square/2 that is reversible - you can use it for square roots
as long as the root is integer.  Integers are represented as 
1 = s(0), 2 = s(s(0)) etc. Enjoy...

Steve 

square(N,M) :- times(N,N,M).

times(s(0),N,N).

times(N,M,P) :-
	add(N1,s(0),N),
	times(N1,M,P1),
	add(M,P1,P).

add(X,0,X).
add(X,s(Y),s(Z)) :- add(X,Y,Z).


succ(0,0) :- !.
succ(N,s(SM)) :- M is N - 1, succ(M,SM).

fore057@canterbury.ac.nz (08/10/12)

In article <1990Aug08.001233.6587@hoss.unl.edu>, sanjiv@fergvax.unl.edu (Sanjiv K. Bhatia) writes:
> Hi there:
> 
> I am working on some experiments using Prolog and need a square root function.
> Will some kind soul mail me a copy of the same if you happen to have one handy?
> 
> Thanks in advance.
> 
> Sanjiv
> Sanjiv K. Bhatia				Department of Computer Science
> sanjiv@fergvax.unl.edu				Ferguson Hall 115
> voice: (402)-472-3485				University of Nebraska - Lincoln
> fax  : (402)-472-7767				Lincoln, NE 68588-0115

If you have log and exponential functions in your prolog version, the following
will give you X to any power Y:

     powerOf(X,Y,Ans):-
             Ans=EXP(Y*LN(X)).