RosettaCodeData/Task/Nth-root/Phix/nth-root.phix

34 lines
722 B
Plaintext

function pow_(atom x, integer e)
atom r = 1
for i=1 to e do
r *= x
end for
return r
end function
function nth_root(atom y,n)
atom eps = 1e-15 -- relative accuracy
atom x = 1
while 1 do
-- atom d = ( y / power(x,n-1) - x ) / n
atom d = ( y / pow_(x,n-1) - x ) / n
x += d
atom e = eps*x -- absolute accuracy
if d > -e and d < e then exit end if
end while
return {y,n,x,power(y,1/n)}
end function
?nth_root(1024,10)
?nth_root(27,3)
?nth_root(2,2)
?nth_root(5642,125)
--?nth_root(7,0.5) -- needs power(), not pow_()
?nth_root(4913,3)
?nth_root(8,3)
?nth_root(16,2)
?nth_root(16,4)
?nth_root(125,3)
?nth_root(1000000000,3)
?nth_root(1000000000,9)