RosettaCodeData/Task/Nth-root/Bc/nth-root.bc

31 lines
536 B
Plaintext

/* Take the nth root of 'a' (a positive real number).
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
*/
define r(a, n, d) {
auto e, o, x, y, z
if (n == 0) return(1)
if (a == 0) return(0)
o = scale
scale = d
e = 1 / 10 ^ d
if (n < 0) {
n = -n
a = 1 / a
}
x = 1
while (1) {
y = ((n - 1) * x + a / x ^ (n - 1)) / n
z = x - y
if (z < 0) z = -z
if (z < e) break
x = y
}
scale = o
return(y)
}