RosettaCodeData/Task/Nth-root/DuckDB/nth-root.duckdb
2025-08-11 18:05:26 -07:00

20 lines
546 B
Text

# Newton's method, assuming a > 0 and n > 0
create or replace function nth_root(a,n) as (
with recursive cte as (
select 0 as ix, a::DOUBLE as x, (a-1.0)::DOUBLE as xprime
union all
select ix+1 as ix,
((n - 1) * x / n ) + (a / (n * x ** (n-1))) as x,
x as xprime
from cte
where @(x - xprime) > 1e-15
and ix<10
)
select last(x order by ix)
from cte
);
select n,
5.0 ^ (1 / cast(n as double)) as builtin,
nth_root(5.0, n) as nth_root
from unnest( [1,3,5,10,1000,10000] ) _(n);