/* 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 => L = [[2,2], [34,5], [34**5,5], [7131.5**10], [7,0.5], [1024,10], [5642, 125] ], foreach([A,N] in L) R = nthroot(A,N), printf("nthroot(%8w,%8w) %20w (check: %w)\n",A,N,R,A**(1/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).