/*
Nth root (Rosetta code) in Picat.
http://rosettacode.org/wiki/Nth_root
"""
Implement the algorithm to compute the principal nth root sqrt[n]A of a
positive real number A, as explained at the Wikipedia page.
"""
See:
http://en.wikipedia.org/wiki/Nth_root
http://en.wikipedia.org/wiki/Nth_root_algorithm
This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com
See also my Picat page: http://www.hakank.org/picat/
*/
main => go.
go =>
println(nthroot(34,5,0.0000000001)),
println(nthroot(7**2,2,10**(-5))),
println(nthroot(5642,125,10**(-5))),
println(nthroot(5642,125,10**(-15))),
L = [[2,2],
[34,5],
[34**5,5],
[7131.5**10],
[7,0.5],
[1024,10],
[5642, 125]
],
foreach([A,N] in L)
println((A,N)=nthroot(A,N))
end,
nl.
%
% x^n = a
%
% Given a and n, find x (to Precision)
%
nthroot(A,N) = nthroot(A,N,0.000001).
nthroot(A,N,Precision) = X1 =>
NF = N * 1.0, % float version of N
X0 = A / NF,
X1 = 1.0,
do
X0 := X1,
X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1))))
while( abs(X0-X1) > Precision).