Nth root: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 10:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F nthroot(a, n)
V result = a
V x = a / n
Line 20:
print(nthroot(34.0, 5))
print(nthroot(42.0, 10))
print(nthroot(5.0, 2))</langsyntaxhighlight>
 
{{out}}
Line 33:
The 'include' file FORMAT, to format a floating point number, can be found in:
[[360_Assembly_include|Include files 360 Assembly]].
<langsyntaxhighlight lang="360asm">* Nth root - x**(1/n) - 29/07/2018
NTHROOT CSECT
USING NTHROOT,R13 base register
Line 91:
PG DC CL80' ' buffer
REGEQU
END NTHROOT </langsyntaxhighlight>
{{out}}
<pre> 1.414213</pre>
Line 97:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program nroot64.s */
Line 207:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 217:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:REALMATH.ACT"
 
PROC NthRoot(REAL POINTER a,n REAL POINTER res)
Line 262:
Test("7","0.5")
Test("12.34","56.78")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Nth_root.png Screenshot from Atari 8-bit computer]
Line 275:
=={{header|Ada}}==
The implementation is generic and supposed to work with any floating-point type. There is no result accuracy argument of Nth_Root, because the iteration is supposed to be monotonically descending to the root when starts at ''A''. Thus it should converge when this condition gets violated, i.e. when ''x''<sub>''k''+1</sub>''&ge;''x''<sub>''k''</sub>''.
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
 
Line 303:
Put_Line ("5642.0 125th =" & Long_Float'Image (Long_Nth_Root (5642.0, 125)));
end Test_Nth_Root;
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 319:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - missing transput, and missing extended precision}}
<langsyntaxhighlight lang="algol68">REAL default p = 0.001;
PROC nth root = (INT n, LONG REAL a, p)LONG REAL:
Line 343:
10 ROOT ( LONG 7131.5 ** 10 ),
5 ROOT 34))
)</langsyntaxhighlight>
Output:
<pre>
Line 354:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% nth root algorithm %
% returns the nth root of A, A must be > 0 %
Line 378:
write( nthRoot( 7131.5 ** 10, 10, 1'-5 ) );
write( nthRoot( 64, 6, 1'-5 ) );
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 387:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program nroot.s */
Line 490:
dfPrec: .double 0f1E-10 @ précision
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">nthRoot: function [a,n][
N: to :floating n
result: a
Line 507:
print nthRoot 34.0 5
print nthRoot 42.0 10
print nthRoot 5.0 2</langsyntaxhighlight>
 
{{out}}
Line 516:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">p := 0.000001
 
MsgBox, % nthRoot( 10, 7131.5**10, p) "`n"
Line 534:
}
Return, x2
}</langsyntaxhighlight>
Message box shows:
<pre>7131.500000
Line 542:
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
$A=4913
$n=3
Line 567:
EndIf
Return nth_root_rec($A,$n,((($n-1)*$x)+($A/$x^($n-1)))/$n)
EndFunc</langsyntaxhighlight>
output :
<pre>20
Line 579:
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
BEGIN {
Line 602:
return x
}
</syntaxhighlight>
</lang>
 
Sample output:
Line 620:
This function is fairly generic MS BASIC. It could likely be used in most modern BASICs with little or no change.
 
<langsyntaxhighlight lang="qbasic">FUNCTION RootX (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE) AS DOUBLE
DIM tmp1 AS DOUBLE, tmp2 AS DOUBLE
' Initial guess:
Line 630:
LOOP WHILE (ABS(tmp1 - tmp2) > diffLimit)
RootX = tmp1
END FUNCTION</langsyntaxhighlight>
 
Note that for the above to work in QBasic, the function definition needs to be changed like so:
<langsyntaxhighlight lang="qbasic">FUNCTION RootX# (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE)</langsyntaxhighlight>
 
The function is called like so:
 
<langsyntaxhighlight lang="qbasic">PRINT "The "; e; "th root of "; b; " is "; RootX(b, e, .000001)</langsyntaxhighlight>
 
Sample output:
Line 648:
=={{header|Basic09}}==
{{Works with |OS9 operating system -- RUN nth(root,number,precision)}}
<syntaxhighlight lang="basic09">
<lang Basic09>
PROCEDURE nth
PARAM N : INTEGER; A, P : REAL
Line 662:
PRINT "The Root is: ";TEMP1
END
</syntaxhighlight>
</lang>
 
=={{header|BASIC256}}==
<langsyntaxhighlight lang="freebasic">function nth_root(n, a)
precision = 0.0001
 
Line 688:
tmp = nth_root(n, 5643)
print n; " "; tmp; chr(9); (tmp ^ n)
next n</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT 64
@% = &D0D
PRINT "Cube root of 5 is "; FNroot(3, 5, 0)
Line 704:
SWAP x0, x1
UNTIL ABS (x0 - x1) <= d
= x0</langsyntaxhighlight>
'''Output:'''
<pre>
Line 712:
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">/* Take the nth root of 'a' (a positive real number).
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
Line 741:
scale = o
return(y)
}</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 750:
<code>_while_</code> is a [https://mlochbaum.github.io/bqncrate/ BQNcrate] idiom used for unbounded looping here.
 
<langsyntaxhighlight lang="bqn">_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Root ← √
Root1 ← ⋆⟜÷˜
Line 771:
•Show 3 Root1 5
•Show 3 Root2 5
•Show 3 Root2 5‿1E¯16</langsyntaxhighlight>
<syntaxhighlight lang="text">1.7099759466766968
1.7099759466766968
1.7099759641072136
1.709975946676697</langsyntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=X3doaWxlXyDihpAge/CdlL3ijZ/wnZS+4oiY8J2UvV/wnZWjX/CdlL7iiJjwnZS94o2f8J2UvvCdlal9ClJvb3Qg4oaQIOKImgpSb290MSDihpAg4ouG4p+cw7fLnApSb290MiDihpAgewogIG4g8J2ViiBh4oC/cHJlYzoKICAx4oqRewogICAgcOKAv3g6CiAgICDin6gKICAgICAgeAogICAgICAoKHAgw5cgbiAtIDEpICsgYSDDtyBwIOKLhiBuIC0gMSkgw7cgbgogICAg4p+pCiAgfSBfd2hpbGVfIHsKICAgIHDigL94OgogICAgcHJlYyDiiaQgfCBwIC0geAogIH0g4p+oYSwg4oyKYcO3buKfqTsKICDwnZWoIPCdlYog8J2VqTog8J2VqCDwnZWKIPCdlanigL8xRcKvNQp9CgrigKJTaG93IDMgUm9vdCA1CuKAolNob3cgMyBSb290MSA1CuKAolNob3cgMyBSb290MiA1CuKAolNob3cgMyBSb290MiA14oC/MUXCrzE2Cgo= Try It!]
=={{header|Bracmat}}==
Bracmat does not have floating point numbers as primitive type. Instead we have to use rational numbers. This code is not fast!
<langsyntaxhighlight lang="bracmat">( ( root
= n a d x0 x1 d2 rnd 10-d
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
Line 808:
& show$(2,2,100)
& show$(125,5642,20)
)</langsyntaxhighlight>
Output:
<pre>1024^(1/10)=2,00000000000000000000*10E0
Line 817:
=={{header|C}}==
Implemented without using math library, because if we were to use <code>pow()</code>, the whole exercise wouldn't make sense.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <float.h>
 
Line 851:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Almost exactly how C works.
<langsyntaxhighlight lang="csharp">
static void Main(string[] args)
{
Line 877:
return x[0];
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
 
<langsyntaxhighlight lang="cpp">double NthRoot(double m_nValue, double index, double guess, double pc)
{
double result = guess;
Line 893:
return result;
};
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="cpp">double NthRoot(double value, double degree)
{
return pow(value, (double)(1 / degree));
};
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">
(ns test-project-intellij.core
(:gen-class))
Line 928:
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion
 
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. Nth-Root.
Line 1,031:
END-PROGRAM.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,054:
=={{header|CoffeeScript}}==
 
<langsyntaxhighlight lang="coffeescript">
nth_root = (A, n, precision=0.0000000000001) ->
x = 1
Line 1,081:
root = nth_root x, n
console.log "#{x} root #{n} = #{root} (root^#{n} = #{Math.pow root, n})"
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="text">
> coffee nth_root.coffee
8 root 3 = 2 (root^3 = 8)
Line 1,096:
100 root 5 = 2.5118864315095806 (root^5 = 100.0000000000001)
100 root 10 = 1.5848931924611134 (root^10 = 99.99999999999993)
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 1,102:
This version does not check for cycles in <var>x<sub>i</sub></var> and <var>x<sub>i+1</sub></var>, but finishes when the difference between them drops below <var>ε</var>. The initial guess can be provided, but defaults to <var>n-1</var>.
 
<langsyntaxhighlight lang="lisp">(defun nth-root (n a &optional (epsilon .0001) (guess (1- n)))
(assert (and (> n 1) (> a 0)))
(flet ((next (x)
Line 1,110:
(do* ((xi guess xi+1)
(xi+1 (next xi) (next xi)))
((< (abs (- xi+1 xi)) epsilon) xi+1))))</langsyntaxhighlight>
 
<code>nth-root</code> may return rationals rather than floating point numbers, so easy checking for correctness may require coercion to floats. For instance,
 
<langsyntaxhighlight lang="lisp">(let* ((r (nth-root 3 10))
(rf (coerce r 'float)))
(print (* r r r ))
(print (* rf rf rf)))</langsyntaxhighlight>
 
produces the following output.
Line 1,125:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.math;
 
real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
Line 1,137:
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(6, 64));
}</langsyntaxhighlight>
{{out}}
<pre>7131.5
Line 1,143:
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">
USES
Math;
Line 1,159:
Result := x_p;
end;
</syntaxhighlight>
</lang>
 
=={{header|E}}==
Line 1,167:
(Disclaimer: This was not written by a numerics expert; there may be reasons this is a bad idea. Also, it might be that cycles are always of length 2, which would reduce the amount of calculation needed by 2/3.)
 
<langsyntaxhighlight lang="e">def nthroot(n, x) {
require(n > 1 && x > 0)
def np := n - 1
Line 1,178:
}
return g1
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">func power x n . r .
r = 1
for i range n
Line 1,200:
call nth_root x 10 r
numfmt 0 4
print r</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def nth_root(n, x, precision \\ 1.0e-5) do
f = fn(prev) -> ((n - 1) * prev + x / :math.pow(prev, (n-1))) / n end
Line 1,216:
Enum.each([{2, 2}, {4, 81}, {10, 1024}, {1/2, 7}], fn {n, x} ->
IO.puts "#{n} root of #{x} is #{RC.nth_root(n, x)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 1,228:
=={{header|Erlang}}==
Done by finding the fixed point of a function, which aims to find a value of <var>x</var> for which <var>f(x)=x</var>:
<langsyntaxhighlight lang="erlang">fixed_point(F, Guess, Tolerance) ->
fixed_point(F, Guess, Tolerance, F(Guess)).
fixed_point(_, Guess, Tolerance, Next) when abs(Guess - Next) < Tolerance ->
Next;
fixed_point(F, _, Tolerance, Next) ->
fixed_point(F, Next, Tolerance, F(Next)).</langsyntaxhighlight>
The nth root function algorithm defined on the wikipedia page linked above can advantage of this:
<langsyntaxhighlight lang="erlang">nth_root(N, X) -> nth_root(N, X, 1.0e-5).
nth_root(N, X, Precision) ->
F = fun(Prev) -> ((N - 1) * Prev + X / math:pow(Prev, (N-1))) / N end,
fixed_point(F, X, Precision).</langsyntaxhighlight>
 
=={{header|Excel}}==
Line 1,244:
 
Beside the obvious;
<langsyntaxhighlight Excellang="excel">=A1^(1/B1)</langsyntaxhighlight>
*Cell A1 is the base.
*Cell B1 is the exponent.
Line 1,296:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let nthroot n A =
let rec f x =
Line 1,318:
printf "%A" (nthroot n A)
0
</syntaxhighlight>
</lang>
 
Compiled using <em>fsc nthroot.fs</em> example output:<pre>
Line 1,326:
=={{header|Factor}}==
{{trans|Forth}}
<langsyntaxhighlight lang="factor">USING: kernel locals math math.functions prettyprint ;
 
:: th-root ( a n -- a^1/n )
Line 1,337:
 
34 5 th-root . ! 2.024397458499888
34 5 recip ^ . ! 2.024397458499888</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: th-root { F: a F: n -- a^1/n }
a
begin
Line 1,350:
 
34e 5e th-root f. \ 2.02439745849989
34e 5e 1/f f** f. \ 2.02439745849989</langsyntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program NthRootTest
implicit none
 
Line 1,394:
end function nthroot
 
end program NthRootTest</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 14-01-2019
' compile with: fbc -s console
 
Line 1,437:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> n 5643 ^ 1 / n nth_root ^ n
Line 1,454:
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">window 1
 
local fn NthRoot( root as long, a as long, precision as double ) as double
Line 1,475:
print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )
 
HandleEvents</langsyntaxhighlight>
Output:
<pre>
Line 1,489:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">func root(a float64, n int) float64 {
n1 := n - 1
n1f, rn := float64(n1), 1/float64(n)
Line 1,507:
}
return x
}</langsyntaxhighlight>
 
The above version is for 64 bit wide floating point numbers. The following uses `math/big` Float to implement this same function with 256 bits of precision.
Line 1,513:
''A set of wrapper functions around the somewhat muddled big math library functions is used to make the main function more readable, and also it was necessary to create a power function (Exp) as the library also lacks this function.'' '''The exponent in the limit must be at least one less than the number of bits of precision of the input value or the function will enter an infinite loop!'''
 
<syntaxhighlight lang="go">
<lang go>
import "math/big"
 
Line 1,579:
return x.Cmp(y) == -1
}
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">import static Constants.tolerance
import static java.math.RoundingMode.HALF_UP
 
Line 1,596:
(xNew as BigDecimal).setScale(7, HALF_UP)
}
</syntaxhighlight>
</lang>
 
Test:
<langsyntaxhighlight lang="groovy">class Constants {
static final tolerance = 0.00001
}
Line 1,619:
it.b, it.n, r, it.r)
assert (r - it.r).abs() <= tolerance
}</langsyntaxhighlight>
 
Output:
Line 1,632:
 
Function exits when there's no difference between two successive values.
<langsyntaxhighlight Haskelllang="haskell">n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n)</langsyntaxhighlight>
Use:
<pre>*Main> 2 `nthRoot` 2
Line 1,649:
Or, in applicative terms, with formatted output:
 
<langsyntaxhighlight lang="haskell">nthRoot :: Double -> Double -> Double
nthRoot n x =
fst $
Line 1,676:
rjust n c = drop . length <*> (replicate n c ++)
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</langsyntaxhighlight>
{{Out}}
<pre>Nth roots:
Line 1,685:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">WRITE(Messagebox) NthRoot(5, 34)
WRITE(Messagebox) NthRoot(10, 7131.5^10)
 
Line 1,703:
 
WRITE(Messagebox, Name) 'Cannot solve problem for:', prec, n, A
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
All Icon/Unicon reals are double precision.
<langsyntaxhighlight Iconlang="icon">procedure main()
showroot(125,3)
showroot(27,3)
Line 1,729:
end
 
link printf</langsyntaxhighlight>
 
Output:<pre>3-th root of 125 = 5.0
Line 1,744:
But, since the [[Talk:Nth_root_algorithm#Comparison_to_Non-integer_Exponentiation|talk page discourages]] using built-in facilities, here is a reimplementation, using the [[#E|E]] algorithm:
 
<langsyntaxhighlight lang="j"> '`N X NP' =. (0 { [)`(1 { [)`(2 { [)
iter =. N %~ (NP * ]) + X % ] ^ NP
nth_root =: (, , _1+[) iter^:_ f. ]
10 nth_root 7131.5^10
7131.5</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="java">public static double nthroot(int n, double A) {
return nthroot(n, A, .001);
}
Line 1,769:
}
return x;
}</langsyntaxhighlight>
{{trans|E}}
<langsyntaxhighlight lang="java">public static double nthroot(int n, double x) {
assert (n > 1 && x > 0);
int np = n - 1;
Line 1,785:
private static double iter(double g, int np, int n, double x) {
return (np * g + x / Math.pow(g, np)) / n;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Gives the ''n'':nth root of ''num'', with precision ''prec''. (''n'' defaults to 2 [e.g. sqrt], ''prec'' defaults to 12.)
 
<langsyntaxhighlight lang="javascript">function nthRoot(num, nArg, precArg) {
var n = nArg || 2;
var prec = precArg || 12;
Line 1,800:
return x;
}</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># An iterative algorithm for finding: self ^ (1/n) to the given
# absolute precision if "precision" > 0, or to within the precision
# allowed by IEEE 754 64-bit numbers.
Line 1,833:
else [., ., (./n), n, 0] | _iterate
end
;</langsyntaxhighlight>
'''Example''':
Compare the results of iterative_nth_root and nth_root implemented using builtins
<langsyntaxhighlight lang="jq">def demo(x):
def nth_root(n): log / n | exp;
def lpad(n): tostring | (n - length) * " " + .;
Line 1,845:
# 5^m for various values of n:
"5^(1/ n): builtin precision=1e-10 precision=0",
( (1,-5,-3,-1,1,3,5,1000,10000) | demo(5))</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -n -r -f nth_root_machine_precision.jq
5^(1/ n): builtin precision=1e-10 precision=0
5^(1/ 1): 4.999999999999999 vs 5 vs 5
Line 1,858:
5^(1/ 1000): 1.0016107337527294 vs 1.0016107337527294 vs 1.0016107337527294
5^(1/10000): 1.0001609567433902 vs 1.0001609567433902 vs 1.0001609567433902
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 1,864:
Julia has a built-in exponentiation function <code>A^(1 / n)</code>, but the specification calls for us to use Newton's method (which we iterate until the limits of machine precision are reached):
 
<langsyntaxhighlight lang="julia">function nthroot(n::Integer, r::Real)
r < 0 || n == 0 && throw(DomainError())
n < 0 && return 1 / nthroot(-n, r)
Line 1,880:
 
@show nthroot.(-5:2:5, 5.0)
@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))</langsyntaxhighlight>
 
{{out}}
Line 1,888:
=={{header|Kotlin}}==
{{trans|E}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun nthRoot(x: Double, n: Int): Double {
Line 1,908:
for (number in numbers)
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,919:
=={{header|Lambdatalk}}==
Translation of Scheme
<syntaxhighlight lang="scheme">
<lang Scheme>
{def root
{def good-enough? {lambda {next guess tol}
Line 1,942:
{root {pow 2 10} 10 0.001}
-> 2.000047868581671
</syntaxhighlight>
</lang>
 
=={{header|langur}}==
Line 1,949:
{{works with|langur|0.8}}
{{trans|D}}
<langsyntaxhighlight lang="langur">writeln "operator"
writeln( (7131.5 ^ 10) ^/ 10 )
writeln 64 ^/ 6
Line 1,967:
writeln "calculation"
writeln .nthroot(10, 7131.5 ^ 10, 0.001)
writeln .nthroot(6, 64, 0.001)</langsyntaxhighlight>
 
{{out}}
Line 1,980:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 ));
print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001))
Line 2,003:
end
</syntaxhighlight>
</lang>
First estimate is: 1.071559602191682 ... and better is: 1.071547591944771
125'th root of 5642 by LB's exponentiation operator is 1.071547591944767
Line 2,011:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on nthRoot (x, root)
return power(x, 1.0/root)
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">the floatPrecision = 8 -- only about display/string cast of floats
put nthRoot(4, 4)
-- 1.41421356</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to about :a :b
output and [:a - :b < 1e-5] [:a - :b > -1e-5]
end
Line 2,029:
end
 
show root 5 34 ; 2.02439745849989</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function nroot(root, num)
return num^(1/root)
end
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 2,065:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function Root (a, n%, d as double=1.e-4) {
Line 2,090:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
 
The <code>root</code> command performs this task.
<syntaxhighlight lang="maple">
<lang Maple>
root(1728, 3);
 
Line 2,101:
 
root(2.0, 2);
</syntaxhighlight>
</lang>
 
Output:
Line 2,113:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang Mathematica="mathematica">Root[A,n]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function answer = nthRoot(number,root)
 
format long
Line 2,128:
end
 
end</langsyntaxhighlight>
 
Sample Output:
<langsyntaxhighlight MATLABlang="matlab">>> nthRoot(2,2)
 
ans =
 
1.414213562373095</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">nth_root(a, n) := block(
[x, y, d, p: fpprec],
fpprec: p + 10,
Line 2,150:
fpprec: p,
bfloat(y)
)$</langsyntaxhighlight>
 
=={{header|Metafont}}==
Metafont does not use IEEE floating point and we can't go beyond 0.0001 or it will loop forever.
<langsyntaxhighlight lang="metafont">vardef mnthroot(expr n, A) =
x0 := A / n;
m := n - 1;
Line 2,170:
show 0.5 nthroot 7; % 49.00528
 
bye</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">1/x <-> x^y С/П</langsyntaxhighlight>
Instruction: ''number'' ^ ''degree'' В/О С/П
 
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="netrexx">
/*NetRexx program to calculate the Nth root of X, with DIGS accuracy. */
class nth_root
Line 2,258:
return _/1 /*normalize the number to digs. */
 
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(define (nth-root n a)
(let ((x1 a)
(x2 (div a n)))
Line 2,271:
(div a (pow x1 (- n 1))))
n)))
x2))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import math
 
proc nthRoot(a: float; n: int): float =
Line 2,286:
echo nthRoot(34.0, 5)
echo nthRoot(42.0, 10)
echo nthRoot(5.0, 2)</langsyntaxhighlight>
Output:
<pre>2.024397458499885
Line 2,294:
=={{header|Objeck}}==
{{trans|C}}
<langsyntaxhighlight lang="objeck">class NthRoot {
function : Main(args : String[]) ~ Nil {
NthRoot(5, 34, .001)->PrintLine();
Line 2,311:
return x[1];
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
{{trans|C}}
<langsyntaxhighlight lang="ocaml">let nthroot ~n ~a ?(tol=0.001) () =
let nf = float n in let nf1 = nf -. 1.0 in
let rec iter x =
Line 2,326:
Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ());
Printf.printf "%g\n" (nthroot 5 34.0 ());
;;</langsyntaxhighlight>
 
=={{header|Octave}}==
Octave has it's how <tt>nthroot</tt> function.
<langsyntaxhighlight lang="octave">
r = A.^(1./n)
</syntaxhighlight>
</lang>
 
Here it is another implementation (after Tcl)
 
{{trans|Tcl}}
<langsyntaxhighlight lang="octave">function r = m_nthroot(n, A)
x0 = A / n;
m = n - 1;
Line 2,348:
x0 = x1;
endwhile
endfunction</langsyntaxhighlight>
 
Here is an more elegant way by computing the successive differences in an explicit way:
<langsyntaxhighlight lang="octave">function r = m_nthroot(n, A)
r = A / n;
m = n - 1;
Line 2,358:
r+= d;
until (abs(d) < abs(r * 1e-9))
endfunction</langsyntaxhighlight>
 
Show its usage and the built-in <tt>nthroot</tt> function
 
<langsyntaxhighlight lang="octave">m_nthroot(10, 7131.5 .^ 10)
nthroot(7131.5 .^ 10, 10)
m_nthroot(5, 34)
nthroot(34, 5)
m_nthroot(0.5, 7)
nthroot(7, .5)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">Float method: nthroot(n)
1.0 doWhile: [ self over n 1 - pow / over - n / tuck + swap 0.0 <> ] ;</langsyntaxhighlight>
 
{{out}}
Line 2,387:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {NthRoot NInt A}
N = {Int.toFloat NInt}
Line 2,405:
end
in
{Show {NthRoot 2 2.0}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">root(n,A)=A^(1/n);</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,415:
=={{header|Perl}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="perl">use strict;
 
sub nthroot ($$)
Line 2,428:
$x0 = $x1;
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">print nthroot(5, 34), "\n";
print nthroot(10, 7131.5 ** 10), "\n";
print nthroot(0.5, 7), "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
Main loop copied from AWK, and as per C uses pow_() instead of power() since using the latter would make the whole exercise somewhat pointless.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pow_</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
Line 2,464:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1024</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">27</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5642</span><span style="color: #0000FF;">,</span><span style="color: #000000;">125</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4913</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">125</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1000000000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1000000000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">}},</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
Note that a {7,0.5} test would need to use power() instead of pow_().
{{out}}
Line 2,482:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def nthroot
var n var y
1e-15 var eps /# relative accuracy #/
Line 2,508:
"The " e "th root of " b " is " b 1 e / power " (" b e nthroot ")" 9 tolist
printList drop nl
endfor</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">function nthroot($number, $root, $p = P)
{
$x[0] = $number;
Line 2,521:
}
return $x[1];
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
L = [[2,2],
[34,5],
Line 2,553:
X0 := X1,
X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1))))
while( abs(X0-X1) > Precision).</langsyntaxhighlight>
 
{{out}}
Line 2,564:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de nthRoot (N A)
Line 2,580:
(prinl (format (nthRoot 2 2.0) *Scl))
(prinl (format (nthRoot 3 12.3) *Scl))
(prinl (format (nthRoot 4 45.6) *Scl))</langsyntaxhighlight>
Output:
<pre>1.414214
Line 2,587:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* Finds the N-th root of the number A */
root: procedure (A, N) returns (float);
declare A float, N fixed binary;
Line 2,599:
end;
return (xi);
end root;</langsyntaxhighlight>
Results:
<pre>
Line 2,611:
=={{header|PowerShell}}==
This sample implementation does not use <code>[System.Math]</code> classes.
<langsyntaxhighlight lang="powershell">#NoTeS: This sample code does not validate inputs
# Thus, if there are errors the 'scary' red-text
# error messages will appear.
Line 2,649:
 
((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)-1)/2</langsyntaxhighlight>
{{Out}}
<pre>PS> .\NTH.PS1
Line 2,663:
=={{header|Prolog}}==
Uses integer math, though via scaling, it can approximate non-integral roots to arbitrary precision.
<syntaxhighlight lang="prolog">
<lang Prolog>
iroot(_, 0, 0) :- !.
iroot(M, N, R) :-
Line 2,685:
newton(2, A, X0, X1) :- X1 is (X0 + A div X0) >> 1, !. % fast special case
newton(N, A, X0, X1) :- X1 is ((N - 1)*X0 + A div X0**(N - 1)) div N.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,710:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#Def_p=0.001
 
Procedure.d Nth_root(n.i, A.d, p.d=#Def_p)
Line 2,728:
Debug Nth_root(125,5642)
Debug "And better:"
Debug Nth_root(125,5642,0.00001)</langsyntaxhighlight>
'''Outputs
125'th root of 5642 is
Line 2,738:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from decimal import Decimal, getcontext
 
def nthroot (n, A, precision):
Line 2,750:
x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1))))
if x_0 == x_1:
return x_1</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python">print nthroot(5, 34, 10)
print nthroot(10,42, 20)
print nthroot(2, 5, 400)</langsyntaxhighlight>
 
Or, in terms of a general '''until''' function:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Nth Root'''
 
from decimal import Decimal, getcontext
Line 2,868:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Nth roots at various precisions:
Line 2,877:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">nthroot <- function(A, n, tol=sqrt(.Machine$double.eps))
{
ifelse(A < 1, x0 <- A * n, x0 <- A / n)
Line 2,888:
}
nthroot(7131.5^10, 10) # 7131.5
nthroot(7, 0.5) # 49</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (nth-root number root (tolerance 0.001))
Line 2,905:
next-guess
(loop next-guess)))
(loop 1.0))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>sub nth-root ($n, $A, $p=1e-9)
{
my $x0 = $A / $n;
Line 2,920:
}
 
say nth-root(3,8);</langsyntaxhighlight>
 
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
<lang RATFOR>
program nth
#
Line 2,959:
 
end
</syntaxhighlight>
</lang>
<pre>
 
Line 2,987:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program calculates the Nth root of X, with DIGS (decimal digits) accuracy. */
parse arg x root digs . /*obtain optional arguments from the CL*/
if x=='' | x=="," then x= 2 /*Not specified? Then use the default.*/
Line 3,024:
if \complex then g=g*sign(Ox) /*adjust the sign (maybe). */
numeric digits oDigs /*reinstate the original digits. */
return (g/1) || left('j', complex) /*normalize # to digs, append j ?*/</langsyntaxhighlight>
'''output''' &nbsp; when using the default inputs:
<pre>
Line 3,069:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(12)
see "cube root of 5 is : " + root(3, 5, 0) + nl
Line 3,082:
end
return x
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,089:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def nthroot(n, a, precision = 1e-5)
x = Float(a)
begin
Line 3,098:
end
 
p nthroot(5,34) # => 2.02439745849989</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print "Root 125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 ))
print "125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 ))
print "125th Root of 5643 Precision .00001 ";using( "#.###############", NthRoot( 125, 5642, 0.00001))
Line 3,121:
end function
end</langsyntaxhighlight>
<pre>125th Root of 5643 Precision .001 1.071559602456735
125th Root of 5643 Precision .00001 1.071547591944771
Line 3,130:
=={{header|Rust}}==
{{trans|Raku}}
<langsyntaxhighlight lang="rust">// 20210212 Rust programming solution
 
fn nthRoot(n: f64, A: f64) -> f64 {
Line 3,146:
fn main() {
println!("{}", nthRoot(3. , 8. ));
}</langsyntaxhighlight>
 
=={{header|Sather}}==
{{trans|Octave}}
<langsyntaxhighlight lang="sather">class MATH is
nthroot(n:INT, a:FLT):FLT
pre n > 0
Line 3,165:
end;
 
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
a:FLT := 2.5 ^ 10.0;
#OUT + MATH::nthroot(10, a) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
Line 3,178:
seems unnecessarily cumbersome, given the ready availability of S-BASIC's built-in exp and
natural log functions.
<langsyntaxhighlight lang="basic">
rem - return nth root of x
function nthroot(x, n = real) = real
Line 3,194:
 
end
</syntaxhighlight>
</lang>
But if the six or seven digits supported by S-BASIC's single-precision REAL data type is insufficient, Newton's Method is the way to go, given that the built-in exp and natural log functions are only single-precision.
<langsyntaxhighlight lang="basic">
rem - return the nth root of real.double value x to stated precision
function nthroot(n, x, precision = real.double) = real.double
Line 3,220:
 
end
</syntaxhighlight>
</lang>
{{out}}
From the second version of the program.
Line 3,239:
=={{header|Scala}}==
Using tail recursion:
<langsyntaxhighlight Scalalang="scala">def nroot(n: Int, a: Double): Double = {
@tailrec
def rec(x0: Double) : Double = {
Line 3,247:
rec(a)
}</langsyntaxhighlight>
 
Alternatively, you can implement the iteration with an iterator like so:
<langsyntaxhighlight lang="scala">def fallPrefix(itr: Iterator[Double]): Iterator[Double] = itr.sliding(2).dropWhile(p => p(0) > p(1)).map(_.head)
def nrootLazy(n: Int)(a: Double): Double = fallPrefix(Iterator.iterate(a){r => (((n - 1)*r) + (a/math.pow(r, n - 1)))/n}).next</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (root number degree tolerance)
(define (good-enough? next guess)
(< (abs (- next guess)) tolerance))
Line 3,271:
(newline)
(display (root (expt 2 10) 10 0.001))
(newline)</langsyntaxhighlight>
Output:
2.04732932236839
Line 3,282:
An alternate function which uses Newton's method is:
 
<langsyntaxhighlight lang="seed7">const func float: nthRoot (in integer: n, in float: a) is func
result
var float: x1 is 0.0;
Line 3,294:
x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n);
end while;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#nthRoot]
Line 3,300:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func nthroot(n, a, precision=1e-5) {
var x = 1.float
var prev = 0.float
Line 3,310:
}
 
say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204</langsyntaxhighlight>
 
A minor optimization would be to calculate the successive ''int(n-1)'' square roots of a number, then raise the result to the power of ''2**(int(n-1) / n)''.
 
<langsyntaxhighlight lang="ruby">func nthroot_fast(n, a, precision=1e-5) {
{ a = nthroot(2, a, precision) } * int(n-1)
a ** (2**int(n-1) / n)
}
 
say nthroot_fast(5, 34, 1e-64) # => 2.02439745849988504251081724554193741911462170107</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 3,325:
 
{{trans|Tcl}}
<langsyntaxhighlight lang="smalltalk">Number extend [
nthRoot: n [
|x0 m x1|
Line 3,337:
]
]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">(34 nthRoot: 5) displayNl.
((7131.5 raisedTo: 10) nthRoot: 10) displayNl.
(7 nthRoot: 0.5) displayNl.</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">nthr(n,r) <= n^(1/r)
 
nthroot(n,r)=
Line 3,357:
 
#.output(nthr(2,2))
#.output(nthroot(2,2))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,366:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension FloatingPoint where Self: ExpressibleByFloatLiteral {
@inlinable
public func power(_ e: Int) -> Self {
Line 3,401:
 
print(81.root(n: 4))
print(13.root(n: 5))</langsyntaxhighlight>
 
{{out}}
Line 3,410:
=={{header|Tcl}}==
The easiest way is to just use the <code>pow</code> function (or exponentiation operator) like this:
<langsyntaxhighlight lang="tcl">proc nthroot {n A} {
expr {pow($A, 1.0/$n)}
}</langsyntaxhighlight>
However that's hardly tackling the problem itself. So here's how to do it using Newton-Raphson and a self-tuning termination test.<br>
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">proc nthroot {n A} {
set x0 [expr {$A / double($n)}]
set m [expr {$n - 1.0}]
Line 3,425:
set x0 $x1
}
}</langsyntaxhighlight>
Demo:
<langsyntaxhighlight lang="tcl">puts [nthroot 2 2]
puts [nthroot 5 34]
puts [nthroot 5 [expr {34**5}]]
puts [nthroot 10 [expr 7131.5**10]]
puts [nthroot 0.5 7]; # Squaring!</langsyntaxhighlight>
Output:
<pre>1.414213562373095
Line 3,440:
 
=={{header|True BASIC}}==
<langsyntaxhighlight lang="qbasic">FUNCTION Nroot (n, a)
LET precision = .00001
 
Line 3,471:
PRINT USING "####.########": (tmp ^ n)
NEXT n
END</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,478:
Error is on the order of machine precision because the stopping
criterion is either a fixed point or a repeating cycle.
<langsyntaxhighlight Ursalalang="ursala">#import nat
#import flo
 
Line 3,485:
-+
("n","n-1"). "A". ("x". div\"n" plus/times("n-1","x") div("A",pow("x","n-1")))^== 1.,
float^~/~& predecessor+-</langsyntaxhighlight>
This implementation is unnecessary in practice due to the availability of the library
function pow, which performs exponentiation and allows fractional exponents.
Here is a test program.
<langsyntaxhighlight Ursalalang="ursala">#cast %eL
 
examples =
Line 3,497:
nthroot5 34.,
nthroot5 pow(34.,5.),
nthroot10 pow(7131.5,10.)></langsyntaxhighlight>
output:
<pre>
Line 3,510:
{{trans|Phix}}
The internal power operator "^" is used in stead of an auxiliary pow_ function and the accuracy has been reduced.
<langsyntaxhighlight lang="vb">Private Function nth_root(y As Double, n As Double)
Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy
Dim x As Variant: x = 1
Line 3,536:
nth_root 1000000000, 3
nth_root 1000000000, 9
End Sub</langsyntaxhighlight>{{out}}
<pre> 1024 10 2 2
27 3 3 3
Line 3,553:
=={{header|Wren}}==
{{trans|E}}
<langsyntaxhighlight lang="ecmascript">var nthRoot = Fn.new { |x, n|
if (n < 2) Fiber.abort("n must be more than 1")
if (x <= 0) Fiber.abort("x must be positive")
Line 3,570:
for (trio in trios) {
System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))")
}</langsyntaxhighlight>
 
{{out}}
Line 3,580:
 
=={{header|XBS}}==
<langsyntaxhighlight XBSlang="xbs">func nthRoot(x,a){
send x^(1/a);
}{a=2};
log(nthRoot(8,3));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,590:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func real NRoot(A, N); \Return the Nth root of A
Line 3,610:
RlOut(0, NRoot(27., 3.)); CrLf(0);
RlOut(0, NRoot(1024.,10.)); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 3,622:
=={{header|Yabasic}}==
{{trans|AWK}}
<langsyntaxhighlight Yabasiclang="yabasic">data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0
 
do
Line 3,644:
return x
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="zkl">fcn nthroot(nth,a,precision=1.0e-5){
x:=prev:=a=a.toFloat(); n1:=nth-1;
do{
Line 3,658:
}
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041</langsyntaxhighlight>
 
 
10,333

edits