Nth root: Difference between revisions

28,744 bytes added ,  17 days ago
Add SmallBASIC
m (→‎{{header|Haskell}}: Minor update to format of output.)
(Add SmallBASIC)
 
(45 intermediate revisions by 26 users not shown)
Line 6:
 
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F nthroot(a, n)
V result = a
V x = a / n
L abs(result - x) > 10e-15
x = result
result = (1.0 / n) * (((n - 1) * x) + (a / pow(x, n - 1)))
R result
 
print(nthroot(34.0, 5))
print(nthroot(42.0, 10))
print(nthroot(5.0, 2))</syntaxhighlight>
 
{{out}}
<pre>
2.0244
1.4532
2.23607
</pre>
 
=={{header|360 Assembly}}==
Line 11 ⟶ 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 69 ⟶ 91:
PG DC CL80' ' buffer
REGEQU
END NTHROOT </langsyntaxhighlight>
{{out}}
<pre> 1.414213</pre>
Line 75 ⟶ 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 185 ⟶ 207:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Root= +2.000000000000000
Root= +1.414213562373095
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
 
PROC NthRoot(REAL POINTER a,n REAL POINTER res)
REAL n1,eps,one,tmp1,tmp2,tmp3
ValR("0.0001",eps)
IntToReal(1,one)
RealSub(n,one,n1)
 
Sqrt(a,res) ;res=sqrt(a)
DO
Power(res,n,tmp1) ;tmp=res^n
RealSub(a,tmp1,tmp2) ;tmp2=a-res^n
RealAbs(tmp2,tmp1) ;tmp1=abs(a-res^n)
IF RealGreaterOrEqual(eps,tmp1) THEN
RETURN
FI
 
Power(res,n1,tmp1) ;tmp1=res^(n-1)
RealDiv(a,tmp1,tmp2) ;tmp2=a/(res^(n-1))
RealMult(n1,res,tmp1) ;tmp1=(n-1)*res
RealAdd(tmp1,tmp2,tmp3) ;tmp3=((n-1)*res + a/(res^(n-1)))
RealDiv(tmp3,n,res) ;res=((n-1)*res + a/(res^(n-1)))/n
OD
RETURN
 
PROC Test(CHAR ARRAY sa,sn)
REAL a,n,res
 
ValR(sa,a)
ValR(sn,n)
PrintR(n) Print(" root of ")
PrintR(a) Print(" is ")
NthRoot(a,n,res)
PrintRE(res)
RETURN
 
PROC Main()
Put(125) PutE() ;clear screen
MathInit()
Test("2","2")
Test("81","4")
Test("1024","10")
Test("7","0.5")
Test("12.34","56.78")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Nth_root.png Screenshot from Atari 8-bit computer]
<pre>
2 root of 2 is 1.41421355
4 root of 81 is 3.00000047
10 root of 1024 is 2.00000001
.5 root of 7 is 48.99975418
56.78 root of 12.34 is 1.04524972
</pre>
 
=={{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 222 ⟶ 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 238 ⟶ 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 262 ⟶ 343:
10 ROOT ( LONG 7131.5 ** 10 ),
5 ROOT 34))
)</langsyntaxhighlight>
Output:
<pre>
Line 273 ⟶ 354:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% nth root algorithm %
% returns the nth root of A, A must be > 0 %
Line 297 ⟶ 378:
write( nthRoot( 7131.5 ** 10, 10, 1'-5 ) );
write( nthRoot( 64, 6, 1'-5 ) );
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 306 ⟶ 387:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program nroot.s */
Line 409 ⟶ 490:
dfPrec: .double 0f1E-10 @ précision
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">nthRoot: function [a,n][
N: to :floating n
result: a
x: a / N
while [0.000000000000001 < abs result-x][
x: result
result: (1//n) * add (n-1)*x a/pow x n-1
]
return result
]
 
print nthRoot 34.0 5
print nthRoot 42.0 10
print nthRoot 5.0 2</syntaxhighlight>
 
{{out}}
 
<pre>2.024397458499885
1.453198460282268
2.23606797749979</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">p := 0.000001
 
MsgBox, % nthRoot( 10, 7131.5**10, p) "`n"
Line 430 ⟶ 534:
}
Return, x2
}</langsyntaxhighlight>
Message box shows:
<pre>7131.500000
Line 438 ⟶ 542:
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
$A=4913
$n=3
Line 463 ⟶ 567:
EndIf
Return nth_root_rec($A,$n,((($n-1)*$x)+($A/$x^($n-1)))/$n)
EndFunc</langsyntaxhighlight>
output :
<pre>20
Line 475 ⟶ 579:
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
BEGIN {
Line 498 ⟶ 602:
return x
}
</syntaxhighlight>
</lang>
 
Sample output:
Line 516 ⟶ 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 526 ⟶ 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 542 ⟶ 646:
See also the [[#Liberty BASIC|Liberty BASIC]] and [[#PureBasic|PureBasic]] solutions.
 
==={{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 558 ⟶ 662:
PRINT "The Root is: ";TEMP1
END
</syntaxhighlight>
</lang>
 
==={{header|BBC BASICBASIC256}}===
<syntaxhighlight lang="freebasic">function nth_root(n, a)
precision = 0.0001
 
dim x(2)
x[0] = a
x[1] = a /n
while abs(x[1] - x[0]) > precision
x[0] = x[1]
x[1] = ((n -1.0) * x[1] +a / x[1]^(n -1.0)) / n
end while
return x[1]
end function
 
print " n 5643 ^ 1 / n nth_root ^ n"
print " --------------------------------------"
for n = 3 to 11 step 2
tmp = nth_root(n, 5643)
print " "; n; " "; tmp; chr(9); (tmp ^ n)
next n
print
for n = 25 to 125 step 25
tmp = nth_root(n, 5643)
print n; " "; tmp; chr(9); (tmp ^ n)
next n</syntaxhighlight>
 
==={{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 574 ⟶ 704:
SWAP x0, x1
UNTIL ABS (x0 - x1) <= d
= x0</langsyntaxhighlight>
'''Output:'''
<pre>
Cube root of 5 is 1.709975946677
125th root of 5643 is 1.071549111198
</pre>
 
==={{header|Chipmunk Basic}}===
{{trans|S-BASIC}}
<syntaxhighlight lang="basic">
10 rem Nth root
20 print "Finding the nth root of 144 to 6 decimal places"
30 print " x n root"
40 print "------------------------"
50 for i = 1 to 8
60 print using "### ";144;
70 print using "#### ";i;
80 print using "###.######";nthroot(i,144,1.000000E-07)
90 next i
100 end
1000 sub nthroot(n,x,precision)
1010 rem Returns the nth root of value x to stated precision
1020 x0 = x
1030 x1 = x/n ' - initial guess
1040 while abs(x1-x0) > precision
1050 x0 = x1
1060 x1 = ((n-1)*x1+x/x1^(n-1))/n
1070 wend
1080 nthroot = x1
1090 end sub
</syntaxhighlight>
{{out}}
<pre>
Finding the nth root of 144 to 6 decimal places
x n root
------------------------
144 1 144.000000
144 2 12.000000
144 3 5.241483
144 4 3.464102
144 5 2.701920
144 6 2.289428
144 7 2.033937
144 8 1.861210
</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">precision 6
 
let a = int(rnd * 5999) + 2
 
print "calculating nth root of ", a, "..."
 
for n = 1 to 10
 
gosub nroot
print n, " : ", y
 
next n
 
end
 
sub nroot
 
let p = .00001
 
let x = a
let y = a / n
 
do
 
if abs(x - y) > p then
 
let x = y
let y = ((n - 1) * y + a / y ^ (n - 1)) / n
 
endif
 
wait
 
loop abs(x - y) > p
 
return</syntaxhighlight>
{{out| Output}}<pre>calculating nth root of 634...
1 : 634
2 : 25.179356
3 : 8.590724
4 : 5.017903
5 : 3.634275
6 : 2.930994
7 : 2.513613
8 : 2.240068
9 : 2.048063
10 : 1.906378</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' version 14-01-2019
' compile with: fbc -s console
 
Function nth_root(n As Integer, number As Double) As Double
 
Dim As Double a1 = number / n, a2 , a3
 
Do
a3 = Abs(a2 - a1)
a2 = ((n -1) * a1 + number / a1 ^ (n -1)) / n
Swap a1, a2
Loop Until Abs(a2 - a1) = a3
 
Return a1
 
End Function
 
' ------=< MAIN >=------
 
Dim As UInteger n
Dim As Double tmp
 
Print
Print " n 5643 ^ 1 / n nth_root ^ n"
Print " ------------------------------------"
For n = 3 To 11 Step 2
tmp = nth_root(n, 5643)
Print Using " ### ###.######## ####.########"; n; tmp; tmp ^ n
Next
 
Print
For n = 25 To 125 Step 25
tmp = nth_root(n, 5643)
Print Using " ### ###.######## ####.########"; n; tmp; tmp ^ n
Next
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre> n 5643 ^ 1 / n nth_root ^ n
------------------------------------
3 17.80341642 5643.00000000
5 5.62732516 5643.00000000
7 3.43502583 5643.00000000
9 2.61116581 5643.00000000
11 2.19303907 5643.00000000
 
25 1.41273402 5643.00000000
50 1.18858488 5643.00000000
75 1.12207047 5643.00000000
100 1.09022240 5643.00000000
125 1.07154911 5643.00000000</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1
 
local fn NthRoot( root as long, a as long, precision as double ) as double
double x0, x1
x0 = a : x1 = a /root
while ( abs( x1 - x0 ) > precision )
x0 = x1
x1 = ( ( root -1.0 ) * x1 + a / x1 ^ ( root -1.0 ) ) /root
wend
end fn = x1
 
print " 125th Root of 5643 Precision .001",, using "#.###############"; fn NthRoot( 125, 5642, 0.001 )
print " 125th Root of 5643 Precision .001",, using "#.###############"; fn NthRoot( 125, 5642, 0.001 )
print " 125th Root of 5643 Precision .00001", using "#.###############"; fn NthRoot( 125, 5642, 0.00001 )
print " Cube Root of 27 Precision .00001", using "#.###############"; fn NthRoot( 3, 27, 0.00001 )
print "Square Root of 2 Precision .00001", using "#.###############"; fn NthRoot( 2, 2, 0.00001 )
print "Square Root of 2 Precision .00001", using "#.###############"; sqr(2) // Processor floating point calc deviation
print " 10th Root of 1024 Precision .00001", using "#.###############"; fn NthRoot( 10, 1024, 0.00001 )
print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )
 
HandleEvents</syntaxhighlight>
Output:
<pre>
125th Root of 5643 Precision .001 1.071559602191682
125th Root of 5643 Precision .001 1.071559602191682
125th Root of 5643 Precision .00001 1.071547591944772
Cube Root of 27 Precision .00001 3.000000000000002
Square Root of 2 Precision .00001 1.414213562374690
Square Root of 2 Precision .00001 1.414213562373095
10th Root of 1024 Precision .00001 2.000000000000000
5th Root of 34 Precision .00001 2.024397458499885
</pre>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 ));
print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001))
print "125'th root of 5642 by LB's exponentiation operator is "; using( "#.###############", 5642^(1 /125))
 
print "27^(1 / 3)", using( "#.###############", NthRoot( 3, 27, 0.00001))
print "2^(1 / 2)", using( "#.###############", NthRoot( 2, 2, 0.00001))
print "1024^(1 /10)", using( "#.###############", NthRoot( 10, 1024, 0.00001))
 
wait
 
function NthRoot( n, A, p)
x( 0) =A
x( 1) =A /n
while abs( x( 1) -x( 0)) >p
x( 0) =x( 1)
x( 1) =( ( n -1.0) *x( 1) +A /x( 1)^( n -1.0)) /n
wend
NthRoot =x( 1)
end function
 
end
</syntaxhighlight>
{{out}}
<pre>
First estimate is: 1.071559602191682 ... and better is: 1.071547591944771
125'th root of 5642 by LB's exponentiation operator is 1.071547591944767
27^(1 / 3) 3.000000000000002
2^(1 / 2) 1.414213562374690
1024^(1 /10) 2.000000000000000
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">#Def_p=0.001
 
Procedure.d Nth_root(n.i, A.d, p.d=#Def_p)
Protected Dim x.d(1)
x(0)=A: x(1)=A/n
While Abs(x(1)-x(0))>p
x(0)=x(1)
x(1)=((n-1.0)*x(1)+A/Pow(x(1),n-1.0))/n
Wend
ProcedureReturn x(1)
EndProcedure
 
;//////////////////////////////
Debug "125'th root of 5642 is"
Debug Pow(5642,1/125)
Debug "First estimate is:"
Debug Nth_root(125,5642)
Debug "And better:"
Debug Nth_root(125,5642,0.00001)</syntaxhighlight>
{{out}}
<pre>
125'th root of 5642 is
1.0715475919447675
First estimate is:
1.0715596021916822
And better:
1.0715475919447714
</pre>
 
==={{header|Run BASIC}}===
<syntaxhighlight 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))
print " 3rd Root of 27 Precision .00001 ";using( "#.###############", NthRoot( 3, 27, 0.00001))
print " 2nd Root of 2 Precision .00001 ";using( "#.###############", NthRoot( 2, 2, 0.00001))
print " 10th Root of 1024 Precision .00001 ";using( "#.###############", NthRoot( 10, 1024, 0.00001))
wait
function NthRoot( root, A, precision)
x0 = A
x1 = A /root
while abs( x1 -x0) >precision
x0 = x1
x1 = x1 / 1.0 ' force float
x1 = (( root -1.0) *x1 +A /x1^( root -1.0)) /root
wend
NthRoot =x1
end function
end</syntaxhighlight>
<pre>125th Root of 5643 Precision .001 1.071559602456735
125th Root of 5643 Precision .00001 1.071547591944771
3rd Root of 27 Precision .00001 3.000000000000001
2nd Root of 2 Precision .00001 1.414213562374690
10th Root of 1024 Precision .00001 2.000000000000000</pre>
 
==={{header|S-BASIC}}===
When single precision results are sufficient for the task at hand, resort to Newton's method
seems unnecessarily cumbersome, given the ready availability of S-BASIC's built-in exp and
natural log functions.
<syntaxhighlight lang="basic">
rem - return nth root of x
function nthroot(x, n = real) = real
end = exp((1.0 / n) * log(x))
 
rem - exercise the routine by finding successive roots of 144
var i = integer
 
print "Finding the nth root of x"
print " x n root"
print "-----------------------"
for i = 1 to 8
print using "### #### ###.####"; 144; i; nthroot(144, i)
next i
 
end
</syntaxhighlight>
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.
<syntaxhighlight lang="basic">
rem - return the nth root of real.double value x to stated precision
function nthroot(n, x, precision = real.double) = real.double
var x0, x1 = real.double
x0 = x
x1 = x / n rem - initial guess
while abs(x1 - x0) > precision do
begin
x0 = x1
x1 = ((n-1.0) * x1 + x / x1 ^ (n-1.0)) / n
end
end = x1
 
rem -- exercise the routine
 
var i = integer
print "Finding the nth root of 144 to 6 decimal places"
print " x n root"
print "------------------------"
for i = 1 to 8
print using "### #### ###.######"; 144; i; nthroot(i, 144.0, 1E-7)
next i
 
end
</syntaxhighlight>
{{out}}
From the second version of the program.
<pre>
Finding the nth root of 144 to 6 decimal places
x n root
-------------------------
144 1 144.000000
144 2 12.000000
144 3 5.241483
144 4 3.464102
144 5 2.701920
144 6 2.289428
144 7 2.033937
144 8 1.861210
</pre>
 
==={{header|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
func nthroot(a, n)
precision = .00001
x1 = a
x2 = a / n
repeat
x1 = x2
x2 = ((n - 1) * x2 + a / x2 ^ (n - 1)) / n
until (abs(x2 - x1) < precision)
return x2
end
 
print "Finding the nth root of 144"
print " x n nthroot"
print "------------------------"
for n = 2 to 8
print using "### #### ###.000000"; 144; n; nthroot(144, n)
next
</syntaxhighlight>
{{out}}
<pre>
Finding the nth root of 144
x n nthroot
-------------------------
144 2 12.000000
144 3 5.241483
144 4 3.464102
144 5 2.701920
144 6 2.289428
144 7 2.033937
144 8 1.861210
</pre>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION Nroot (n, a)
LET precision = .00001
 
LET x1 = a
LET x2 = a / n
DO WHILE ABS(x2 - x1) > precision
LET x1 = x2
LET x2 = ((n - 1) * x2 + a / x2 ^ (n - 1)) / n
LOOP
LET Nroot = x2
END FUNCTION
 
PRINT " n 5643 ^ 1 / n nth_root ^ n"
PRINT " ------------------------------------"
FOR n = 3 TO 11 STEP 2
LET tmp = Nroot(n, 5643)
PRINT USING "####": n;
PRINT " ";
PRINT USING "###.########": tmp;
PRINT " ";
PRINT USING "####.########": (tmp ^ n)
NEXT n
PRINT
FOR n = 25 TO 125 STEP 25
LET tmp = Nroot(n, 5643)
PRINT USING "####": n;
PRINT " ";
PRINT USING "###.########": tmp;
PRINT " ";
PRINT USING "####.########": (tmp ^ n)
NEXT n
END</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|AWK}}
<syntaxhighlight lang="yabasic">data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0
 
do
read e, b
if e = 0 break
print "The ", e, "th root of ", b, " is ", b^(1/e), " (", nthroot(b, e), ")"
loop
 
 
sub nthroot(y, n)
local eps, x, d, e
eps = 1e-15 // relative accuracy
x = 1
repeat
d = ( y / ( x^(n-1) ) - x ) / n
x = x + d
e = eps * x // absolute accuracy
until(not(d < -e or d > e ))
return x
end sub</syntaxhighlight>
 
==={{header|VBA}}===
{{trans|Phix}}
The internal power operator "^" is used in stead of an auxiliary pow_ function and the accuracy has been reduced.
<syntaxhighlight 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
Do While True
d = (y / x ^ (n - 1) - x) / n
x = x + d
e = eps * x '-- absolute accuracy
If d > -e And d < e Then
Exit Do
End If
Loop
Debug.Print y; n; x; y ^ (1 / n)
End Function
Public Sub main()
nth_root 1024, 10
nth_root 27, 3
nth_root 2, 2
nth_root 5642, 125
nth_root 7, 0.5
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
End Sub</syntaxhighlight>{{out}}
<pre> 1024 10 2 2
27 3 3 3
2 2 1,41421356237309 1,4142135623731
5642 125 1,07154759194477 1,07154759194477
7 0,5 49 49
4913 3 17 17
8 3 2 2
16 2 4 4
16 4 2 2
125 3 5 5
1000000000 3 1000 1000
1000000000 9 10 10
</pre>
 
=={{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 611 ⟶ 1,215:
scale = o
return(y)
}</langsyntaxhighlight>
 
=={{header|BQN}}==
There are two builtin methods to solve this problem(<code>√</code> and <code>⋆</code>), both give a result at the highest precision possible.
 
<code>Root2</code> is a translation of the [[Run BASIC]] implementation, which uses Newton's approximation method. It allows an optional argument for precision, and otherwise defaults to 10<sup>¯5</sup>.
 
<code>_while_</code> is a [https://mlochbaum.github.io/bqncrate/ BQNcrate] idiom used for unbounded looping here.
 
<syntaxhighlight lang="bqn">_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Root ← √
Root1 ← ⋆⟜÷˜
Root2 ← {
n 𝕊 a‿prec:
1⊑{
p‿x:
x
((p × n - 1) + a ÷ p ⋆ n - 1) ÷ n
} _while_ {
p‿x:
prec ≤ | p - x
} ⟨a, ⌊a÷n⟩;
𝕨 𝕊 𝕩: 𝕨 𝕊 𝕩‿1E¯5
}
 
•Show 3 Root 5
•Show 3 Root1 5
•Show 3 Root2 5
•Show 3 Root2 5‿1E¯16</syntaxhighlight>
<syntaxhighlight lang="text">1.7099759466766968
1.7099759466766968
1.7099759641072136
1.709975946676697</syntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=X3doaWxlXyDihpAge/CdlL3ijZ/wnZS+4oiY8J2UvV/wnZWjX/CdlL7iiJjwnZS94o2f8J2UvvCdlal9ClJvb3Qg4oaQIOKImgpSb290MSDihpAg4ouG4p+cw7fLnApSb290MiDihpAgewogIG4g8J2ViiBh4oC/cHJlYzoKICAx4oqRewogICAgcOKAv3g6CiAgICDin6gKICAgICAgeAogICAgICAoKHAgw5cgbiAtIDEpICsgYSDDtyBwIOKLhiBuIC0gMSkgw7cgbgogICAg4p+pCiAgfSBfd2hpbGVfIHsKICAgIHDigL94OgogICAgcHJlYyDiiaQgfCBwIC0geAogIH0g4p+oYSwg4oyKYcO3buKfqTsKICDwnZWoIPCdlYog8J2VqTog8J2VqCDwnZWKIPCdlanigL8xRcKvNQp9CgrigKJTaG93IDMgUm9vdCA1CuKAolNob3cgMyBSb290MSA1CuKAolNob3cgMyBSb290MiA1CuKAolNob3cgMyBSb290MiA14oC/MUXCrzE2Cgo= Try It!]
=={{header|Bracmat}}==
Until 2023, Bracmat doesdid not have floating point numbers as primitive type. Instead we havehad 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 643 ⟶ 1,282:
& show$(2,2,100)
& show$(125,5642,20)
)</langsyntaxhighlight>
Output:
<pre>1024^(1/10)=2,00000000000000000000*10E0
Line 649 ⟶ 1,288:
2^(1/2)=1,4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727*10E0
5642^(1/125)=1,07154759194476751170*10E0</pre>
 
This is a floating point reimplementation of the C solution:
{{trans|C}}
<syntaxhighlight lang="bracmat"> "The body of Pow will be compiled twice: once as the the code hidden in the
UFP object called 'POW' (see below) and once as a local function of the code
hidden in the UFP object called 'Root' (also see below)."
& ( Pow
= (s.x) (s.e)
. 1:?r
& 0:?i
& whl
' ( !i:<!e
& !x*!r:?r
& 1+!i:?i
)
& !r
)
& "The next expression is a macro expression that expands $Pow to the body of
the Pow function defined above.
There is another local function, called 'even'."
&
' ( (s.n) (s.x)
. (Pow=$Pow)
& ( even
= (s.v)
. floor$(!v*1/2):?v/2
& subtract$(!v,2*!v/2)
)
& ( !x:0
| ( !n:<1
| !x:<0&even$!n:0
)
& divide$(0,0)
| 0x1p-52*10:?EPS
& 0x1p-52*-10:?EPS-
& 1:?r
& !n+-1:?n-1
& whl
' ( divide
$ (divide$(!x,Pow$(!r,!n-1))+-1*!r,!n)
: ?d
& !d+!r:?r
& (!d:~<!EPS|!d:~>!EPS-)
)
& !r
)
)
: (=?root)
& "Create two UFP objects, POW and ROOT. They are each others' inverse."
& new$(UFP,Pow):?POW
& new$(UFP,root):?Root
& 15:?n
& (POW..go)$("-3.14159",15):?x
& out$((Root..go)$(!n,!x));</syntaxhighlight>
 
Output:
 
<pre>-3.1415899999999999E+00</pre>
 
=={{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 686 ⟶ 1,383:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Almost exactly how C works.
<langsyntaxhighlight lang="csharp">
static void Main(string[] args)
{
Line 712 ⟶ 1,409:
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 728 ⟶ 1,425:
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 763 ⟶ 1,460:
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion
 
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. Nth-Root.
Line 865 ⟶ 1,563:
END-PROGRAM.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 888 ⟶ 1,586:
=={{header|CoffeeScript}}==
 
<langsyntaxhighlight lang="coffeescript">
nth_root = (A, n, precision=0.0000000000001) ->
x = 1
Line 915 ⟶ 1,613:
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 930 ⟶ 1,628:
100 root 5 = 2.5118864315095806 (root^5 = 100.0000000000001)
100 root 10 = 1.5848931924611134 (root^10 = 99.99999999999993)
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 936 ⟶ 1,634:
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 944 ⟶ 1,642:
(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 959 ⟶ 1,657:
 
=={{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 971 ⟶ 1,669:
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(6, 64));
}</langsyntaxhighlight>
{{out}}
<pre>7131.5
2</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">import 'dart:math' show pow;
 
num nroot(num value, num degree) {
return pow(value, (1 / degree));
}
 
void main() {
int n = 15;
num x = pow(-3.14159, 15);
print('root($n, $x) = ${nroot(n, x)}');
}</syntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">
USES
Math;
Line 993 ⟶ 1,704:
Result := x_p;
end;
</syntaxhighlight>
</lang>
 
=={{header|E}}==
Line 1,001 ⟶ 1,712:
(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,012 ⟶ 1,723:
}
return g1
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>floatvars
func power x n% . r .
r = 1
for i% range= 1 to n%
r *= x
.
return r
.
func nth_root x n% . r .
r = 2
repeat
call p = power r (n% - 1 p)
d = (x / p - r) / n%
r += d
until absfabs d < 0.0001
.
return r
.
numfmt 4 0
call power 3.1416 10 x
x = power 3.1416 10
call nth_root x 10 r
print r</lang>nth_root x 10
</syntaxhighlight>
 
=={{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,050 ⟶ 1,764:
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,062 ⟶ 1,776:
=={{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,078 ⟶ 1,792:
 
Beside the obvious;
<langsyntaxhighlight Excellang="excel">=A1^(1/B1)</langsyntaxhighlight>
*Cell A1 is the base.
*Cell B1 is the exponent.
Line 1,130 ⟶ 1,844:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let nthroot n A =
let rec f x =
Line 1,152 ⟶ 1,866:
printf "%A" (nthroot n A)
0
</syntaxhighlight>
</lang>
 
Compiled using <em>fsc nthroot.fs</em> example output:<pre>
Line 1,160 ⟶ 1,874:
=={{header|Factor}}==
{{trans|Forth}}
<langsyntaxhighlight lang="factor">USING: kernel locals math math.functions prettyprint ;
 
:: th-root ( a n -- a^1/n )
Line 1,171 ⟶ 1,885:
 
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,184 ⟶ 1,898:
 
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,228 ⟶ 1,942:
end function nthroot
 
end program NthRootTest</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<lang freebasic>' version 14-01-2019
' compile with: fbc -s console
 
Function nth_root(n As Integer, number As Double) As Double
 
Dim As Double a1 = number / n, a2 , a3
 
Do
a3 = Abs(a2 - a1)
a2 = ((n -1) * a1 + number / a1 ^ (n -1)) / n
Swap a1, a2
Loop Until Abs(a2 - a1) = a3
 
Return a1
 
End Function
 
' ------=< MAIN >=------
 
Dim As UInteger n
Dim As Double tmp
 
Print
Print " n 5643 ^ 1 / n nth_root ^ n"
Print " ------------------------------------"
For n = 3 To 11 Step 2
tmp = nth_root(n, 5643)
Print Using " ### ###.######## ####.########"; n; tmp; tmp ^ n
Next
 
Print
For n = 25 To 125 Step 25
tmp = nth_root(n, 5643)
Print Using " ### ###.######## ####.########"; n; tmp; tmp ^ n
Next
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre> n 5643 ^ 1 / n nth_root ^ n
------------------------------------
3 17.80341642 5643.00000000
5 5.62732516 5643.00000000
7 3.43502583 5643.00000000
9 2.61116581 5643.00000000
11 2.19303907 5643.00000000
 
25 1.41273402 5643.00000000
50 1.18858488 5643.00000000
75 1.12207047 5643.00000000
100 1.09022240 5643.00000000
125 1.07154911 5643.00000000</pre>
 
=={{header|FutureBasic}}==
<lang futurebasic>
include "ConsoleWindow"
 
def tab 8
 
local fn NthRoot( root as long, a as long, precision as double ) as double
dim as double x0, x1
 
x0 = a : x1 = a /root
while ( abs( x1 - x0 ) > precision )
x0 = x1
x1 = ( ( root -1.0 ) * x1 + a / x1 ^ ( root -1.0 ) ) /root
wend
end fn = x1
 
print " 125th Root of 5643 Precision .001", using "#.###############"; fn NthRoot( 125, 5642, 0.001 )
print " 125th Root of 5643 Precision .001", using "#.###############"; fn NthRoot( 125, 5642, 0.001 )
print " 125th Root of 5643 Precision .00001", using "#.###############"; fn NthRoot( 125, 5642, 0.00001 )
print " Cube Root of 27 Precision .00001", using "#.###############"; fn NthRoot( 3, 27, 0.00001 )
print "Square Root of 2 Precision .00001", using "#.###############"; fn NthRoot( 2, 2, 0.00001 )
print "Square Root of 2 Precision .00001", using "#.###############"; sqr(2) // Processor floating point calc deviation
print " 10th Root of 1024 Precision .00001", using "#.###############"; fn NthRoot( 10, 1024, 0.00001 )
print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )
</lang>
Output:
<pre>
125th Root of 5643 Precision .001 1.071559602191682
125th Root of 5643 Precision .001 1.071559602191682
125th Root of 5643 Precision .00001 1.071547591944772
Cube Root of 27 Precision .00001 3.000000000000002
Square Root of 2 Precision .00001 1.414213562374690
Square Root of 2 Precision .00001 1.414213562373095
10th Root of 1024 Precision .00001 2.000000000000000
5th Root of 34 Precision .00001 2.024397458499885
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">func root(a float64, n int) float64 {
n1 := n - 1
n1f, rn := float64(n1), 1/float64(n)
Line 1,343 ⟶ 1,963:
}
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,349 ⟶ 1,969:
''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,415 ⟶ 2,035:
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,432 ⟶ 2,052:
(xNew as BigDecimal).setScale(7, HALF_UP)
}
</syntaxhighlight>
</lang>
 
Test:
<langsyntaxhighlight lang="groovy">class Constants {
static final tolerance = 0.00001
}
Line 1,455 ⟶ 2,075:
it.b, it.n, r, it.r)
assert (r - it.r).abs() <= tolerance
}</langsyntaxhighlight>
 
Output:
Line 1,468 ⟶ 2,088:
 
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,485 ⟶ 2,105:
Or, in applicative terms, with formatted output:
 
<langsyntaxhighlight lang="haskell">nthRoot :: Double -> Double -> Double
nthRoot n x =
fst $
until
(uncurry (==))
(((,) <*> ((/ n) . ((+) . ((n - 1)pn *) <*> (x /) . (** (n - 1)pn)))) . snd)
(x, x / n)
where
 
pn = pred n
 
-------------------------- TESTS --------------------------
Line 1,504 ⟶ 2,125:
(uncurry nthRoot)
[(2, 2), (5, 34), (10, 734 ^ 10), (0.5, 7)]
 
 
-------------------- FORMAT OF RESULTS --------------------
Line 1,512 ⟶ 2,132:
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,521 ⟶ 2,141:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">WRITE(Messagebox) NthRoot(5, 34)
WRITE(Messagebox) NthRoot(10, 7131.5^10)
 
Line 1,539 ⟶ 2,159:
 
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,565 ⟶ 2,185:
end
 
link printf</langsyntaxhighlight>
 
Output:<pre>3-th root of 125 = 5.0
Line 1,580 ⟶ 2,200:
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,605 ⟶ 2,225:
}
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,621 ⟶ 2,241:
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,636 ⟶ 2,256:
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,669 ⟶ 2,289:
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,681 ⟶ 2,301:
# 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,694 ⟶ 2,314:
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,700 ⟶ 2,320:
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,716 ⟶ 2,336:
 
@show nthroot.(-5:2:5, 5.0)
@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))</langsyntaxhighlight>
 
{{out}}
Line 1,724 ⟶ 2,344:
=={{header|Kotlin}}==
{{trans|E}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun nthRoot(x: Double, n: Int): Double {
Line 1,744 ⟶ 2,364:
for (number in numbers)
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,752 ⟶ 2,372:
2.0 ^ 1/2 = 1.414213562373095
</pre>
 
=={{header|Lambdatalk}}==
Translation of Scheme
<syntaxhighlight lang="scheme">
{def root
{def good-enough? {lambda {next guess tol}
{< {abs {- next guess}} tol} }}
{def improve {lambda {guess num deg}
{/ {+ {* {- deg 1} guess}
{/ num {pow guess {- deg 1}}}} deg} }}
{def *root {lambda {guess num deg tol}
{let { {guess guess} {num num} {deg deg} {tol tol}
{next {improve guess num deg}}
} {if {good-enough? next guess tol}
then guess
else {*root next num deg tol}} }}}
{lambda {num deg tol}
{*root 1.0 num deg tol} }}
-> root
 
{root {pow 2 10} 10 0.1}
-> 2.0473293223683866
{root {pow 2 10} 10 0.01}
-> 2.004632048354822
{root {pow 2 10} 10 0.001}
-> 2.000047868581671
</syntaxhighlight>
 
=={{header|langur}}==
Langur has a root operator. Here, we show use of both the root operator and an nth root function.
 
{{works with|langur|0.8}}
{{trans|D}}
<syntaxhighlight lang ="langur">writeln "operator"
writeln( (7131.5 ^ 10) ^/ 10 )"operator"
writeln (7131.5 ^ 10) ^/ 10
writeln 64 ^/ 6
writeln()
 
val nthroot = fn(n, A, p) {
var x = [A, A / n]
while abs(x[2]-x[1]) > p {
x = [x[2], ((n-1) * x[2] + A / (x[2] ^ (n-1))) / n]
}
simplify x[2]
}
 
# To make the example from the D language work, we set a low maximum for the number of digits after a decimal point in division.
mode divMaxScale = 7
 
writeln "function"
val .nthroot = f(.n, .A, .p) {
writeln nthroot(10, 7131.5 ^ 10, 0.001)
var .x = [.A, .A / .n]
writeln nthroot(6, 64, 0.001)
while abs(.x[2]-.x[1]) > .p {
</syntaxhighlight>
.x = [.x[2], ((.n-1) x .x[2] + .A / (.x[2] ^ (.n-1))) / .n]
}
simplify .x[2]
}
 
writeln "calculation"
writeln .nthroot(10, 7131.5 ^ 10, 0.001)
writeln .nthroot(6, 64, 0.001)</lang>
 
{{out}}
Line 1,783 ⟶ 2,431:
2
 
function
calculation
7131.5
2
</pre>
 
=={{header|Liberty BASIC}}==
<lang lb>
print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 ));
print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001))
print "125'th root of 5642 by LB's exponentiation operator is "; using( "#.###############", 5642^(1 /125))
 
print "27^(1 / 3)", using( "#.###############", NthRoot( 3, 27, 0.00001))
print "2^(1 / 2)", using( "#.###############", NthRoot( 2, 2, 0.00001))
print "1024^(1 /10)", using( "#.###############", NthRoot( 10, 1024, 0.00001))
 
wait
 
function NthRoot( n, A, p)
x( 0) =A
x( 1) =A /n
while abs( x( 1) -x( 0)) >p
x( 0) =x( 1)
x( 1) =( ( n -1.0) *x( 1) +A /x( 1)^( n -1.0)) /n
wend
NthRoot =x( 1)
end function
 
end
</lang>
First estimate is: 1.071559602191682 ... and better is: 1.071547591944771
125'th root of 5642 by LB's exponentiation operator is 1.071547591944767
27^(1 / 3) 3.000000000000002
2^(1 / 2) 1.414213562374690
1024^(1 /10) 2.000000000000000
 
=={{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 1,838 ⟶ 2,455:
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 1,874 ⟶ 2,491:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function Root (a, n%, d as double=1.e-4) {
Line 1,899 ⟶ 2,516:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
 
The <code>root</code> command performs this task.
<syntaxhighlight lang="maple">
<lang Maple>
root(1728, 3);
 
Line 1,910 ⟶ 2,527:
 
root(2.0, 2);
</syntaxhighlight>
</lang>
 
Output:
Line 1,921 ⟶ 2,538:
</pre>
 
=={{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 1,937 ⟶ 2,554:
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 1,959 ⟶ 2,576:
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 1,979 ⟶ 2,596:
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,067 ⟶ 2,684:
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,080 ⟶ 2,697:
(div a (pow x1 (- n 1))))
n)))
x2))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import math
 
proc nthrootnthRoot(a,: float; n: int): float =
var n = float(n)
result = a
var x = a / n
while abs(result-x) > 10e1e-15:
x = result
result = (1.0/n) * (((n-1)*x) + (a / pow(x, n-1)))
 
echo nthrootnthRoot(34.0, 5)
echo nthrootnthRoot(42.0, 10)
echo nthrootnthRoot(5.0, 2)</langsyntaxhighlight>
Output:
<pre>2.0243974584998852e+00024397458499885
1.453198460282268
1.4531984602822678e+00
2.2360679774997898e+0023606797749979</pre>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
def "math root" [n] {$in ** (1 / $n)}
 
1..10 | each {|it|
1..10 | reduce --fold {index: $it} {|root acc|
$acc | insert $"root ($root)" ($it | math root $root | into string --decimals 4 )
}
}
</syntaxhighlight>
{{out}}
<pre>
╭──────┬───────────┬──────────┬──────────┬──────────┬──────────┬──────────┬──────────┬─────────┬─────────┬──────────╮
│ # │ root 1 │ root 2 │ root 3 │ root 4 │ root 5 │ root 6 │ root 7 │ root 8 │ root 9 │ root 10 │
├──────┼───────────┼──────────┼──────────┼──────────┼──────────┼──────────┼──────────┼─────────┼─────────┼──────────┤
│ 1 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │ 1.0000 │
│ 2 │ 2.0000 │ 1.4142 │ 1.2599 │ 1.1892 │ 1.1487 │ 1.1225 │ 1.1041 │ 1.0905 │ 1.0801 │ 1.0718 │
│ 3 │ 3.0000 │ 1.7321 │ 1.4422 │ 1.3161 │ 1.2457 │ 1.2009 │ 1.1699 │ 1.1472 │ 1.1298 │ 1.1161 │
│ 4 │ 4.0000 │ 2.0000 │ 1.5874 │ 1.4142 │ 1.3195 │ 1.2599 │ 1.2190 │ 1.1892 │ 1.1665 │ 1.1487 │
│ 5 │ 5.0000 │ 2.2361 │ 1.7100 │ 1.4953 │ 1.3797 │ 1.3077 │ 1.2585 │ 1.2228 │ 1.1958 │ 1.1746 │
│ 6 │ 6.0000 │ 2.4495 │ 1.8171 │ 1.5651 │ 1.4310 │ 1.3480 │ 1.2917 │ 1.2510 │ 1.2203 │ 1.1962 │
│ 7 │ 7.0000 │ 2.6458 │ 1.9129 │ 1.6266 │ 1.4758 │ 1.3831 │ 1.3205 │ 1.2754 │ 1.2414 │ 1.2148 │
│ 8 │ 8.0000 │ 2.8284 │ 2.0000 │ 1.6818 │ 1.5157 │ 1.4142 │ 1.3459 │ 1.2968 │ 1.2599 │ 1.2311 │
│ 9 │ 9.0000 │ 3.0000 │ 2.0801 │ 1.7321 │ 1.5518 │ 1.4422 │ 1.3687 │ 1.3161 │ 1.2765 │ 1.2457 │
│ 10 │ 10.0000 │ 3.1623 │ 2.1544 │ 1.7783 │ 1.5849 │ 1.4678 │ 1.3895 │ 1.3335 │ 1.2915 │ 1.2589 │
╰──────┴───────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┴─────────┴─────────┴──────────╯
</pre>
 
=={{header|Objeck}}==
{{trans|C}}
<langsyntaxhighlight lang="objeck">class NthRoot {
function : Main(args : String[]) ~ Nil {
NthRoot(5, 34, .001)->PrintLine();
Line 2,120 ⟶ 2,765:
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,135 ⟶ 2,780:
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,157 ⟶ 2,802:
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,167 ⟶ 2,812:
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,196 ⟶ 2,841:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {NthRoot NInt A}
N = {Int.toFloat NInt}
Line 2,214 ⟶ 2,859:
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,224 ⟶ 2,869:
=={{header|Perl}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="perl">use strict;
 
sub nthroot ($$)
Line 2,237 ⟶ 2,882:
$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.
{{trans|AWK}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
(main loop)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
{{trans|C}}
<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>
(use of pow_ instead of power)<br>
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<lang Phix>function pow_(atom x, integer e)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">e</span> <span style="color: #008080;">do</span>
atom r = 1
<span style="color: #000000;">r</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">x</span>
for i=1 to e do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
r *= x
<span style="color: #008080;">return</span> <span style="color: #000000;">r</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return r
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">nth_root</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">atom</span> <span style="color: #000000;">eps</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1e-15</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- relative accuracy</span>
function nth_root(atom y,n)
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
atom eps = 1e-15 -- relative accuracy
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
atom x = 1
<span style="color: #000080;font-style:italic;">-- atom d = ( y / power(x,n-1) - x ) / n</span>
while 1 do
<span style="color: #004080;">atom</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">pow_</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">)</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">n</span>
-- atom d = ( y / power(x,n-1) - x ) / n
<span style="color: #000000;">x</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">d</span>
atom d = ( y / pow_(x,n-1) - x ) / n
<span style="color: #004080;">atom</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">eps</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span> <span style="color: #000080;font-style:italic;">-- absolute accuracy </span>
x += d
<span style="color: #008080;">if</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">></span> <span style="color: #0000FF;">-</span><span style="color: #000000;">e</span> <span style="color: #008080;">and</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;"><</span> <span style="color: #000000;">e</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
atom e = eps*x -- absolute accuracy
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if d > -e and d < e then exit end if
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return {y,n,x,power(y,1/n)}
end function
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">yn</span><span style="color: #0000FF;">)</span>
?nth_root(1024,10)
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">yn</span>
?nth_root(27,3)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"nth_root(%d,%d) = %.10g, builtin = %.10g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nth_root</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)})</span>
?nth_root(2,2)
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
?nth_root(5642,125)
<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>
--?nth_root(7,0.5) -- needs power(), not pow_()
<!--</syntaxhighlight>-->
?nth_root(4913,3)
Note that a {7,0.5} test would need to use power() instead of pow_().
?nth_root(8,3)
?nth_root(16,2)
?nth_root(16,4)
?nth_root(125,3)
?nth_root(1000000000,3)
?nth_root(1000000000,9)</lang>
{{out}}
Shows inputs and both the iterative and builtin results.
<pre>
nth_root(1024,10) = 2, builtin = 2
{1024,10,2,2}
nth_root(27,3) = 3, builtin = 3
{27,3,3,3}
{nth_root(2,2,1) = 1.414213562,1 builtin = 1.414213562}
{nth_root(5642,125,1) = 1.071547592,1 builtin = 1.071547592}
nth_root(4913,3) = 17, builtin = 17
{4913,3,17,17.0}
nth_root(8,3) = 2, builtin = 2
{8,3,2,2}
nth_root(16,2) = 4, builtin = 4
{16,2,4,4}
nth_root(16,4) = 2, builtin = 2
{16,4,2,2}
nth_root(125,3) = 5, builtin = 5
{125,3,5,5}
{nth_root(1000000000,3) = 1000,1000,1000.0} builtin = 1000
{nth_root(1000000000,9) = 10,10,10.0} builtin = 10
</pre>
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def nthroot
var n var y
1e-15 var eps /# relative accuracy #/
Line 2,324 ⟶ 2,962:
"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,337 ⟶ 2,975:
}
return $x[1];
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">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).</syntaxhighlight>
 
{{out}}
<pre>nthroot( 2, 2) 1.414213562373095 (check: 1.414213562373095)
nthroot( 34, 5) 2.024397458499885 (check: 2.024397458499885)
nthroot(45435424, 5) 34.0 (check: 34.000000000000007)
nthroot( 7, 0.5) 48.999999999999993 (check: 49.0)
nthroot( 1024, 10) 2.0 (check: 2.0)
nthroot( 5642, 125) 1.071547591944767 (check: 1.071547591944767)</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de nthRoot (N A)
Line 2,356 ⟶ 3,034:
(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,363 ⟶ 3,041:
 
=={{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,375 ⟶ 3,053:
end;
return (xi);
end root;</langsyntaxhighlight>
Results:
<pre>
Line 2,387 ⟶ 3,065:
=={{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,425 ⟶ 3,103:
 
((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)-1)/2</langsyntaxhighlight>
{{Out}}
<pre>PS> .\NTH.PS1
Line 2,439 ⟶ 3,117:
=={{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,461 ⟶ 3,139:
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,484 ⟶ 3,162:
X = -3.
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>#Def_p=0.001
 
Procedure.d Nth_root(n.i, A.d, p.d=#Def_p)
Protected Dim x.d(1)
x(0)=A: x(1)=A/n
While Abs(x(1)-x(0))>p
x(0)=x(1)
x(1)=((n-1.0)*x(1)+A/Pow(x(1),n-1.0))/n
Wend
ProcedureReturn x(1)
EndProcedure
 
;//////////////////////////////
Debug "125'th root of 5642 is"
Debug Pow(5642,1/125)
Debug "First estimate is:"
Debug Nth_root(125,5642)
Debug "And better:"
Debug Nth_root(125,5642,0.00001)</lang>
'''Outputs
125'th root of 5642 is
1.0715475919447675
First estimate is:
1.0715596021916822
And better:
1.0715475919447714
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from decimal import Decimal, getcontext
 
def nthroot (n, A, precision):
Line 2,526 ⟶ 3,176:
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,644 ⟶ 3,294:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Nth roots at various precisions:
Line 2,653 ⟶ 3,303:
 
=={{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,664 ⟶ 3,314:
}
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,681 ⟶ 3,331:
next-guess
(loop next-guess)))
(loop 1.0))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>sub nth-root infix:<√>($n, $A,) $p=1e-9){
.tail given $A / $n, { (($n-1) * $_+ $A / ($_** ($n-1))) / $n } ... * ≅ *;
{
my $x0 = $A / $n;
loop {
my $x1 = (($n-1) * $x0 + $A / ($x0 ** ($n-1))) / $n;
return $x1 if abs($x1-$x0) < abs($x0 * $p);
$x0 = $x1;
}
}
 
use Test;
say nth-root(3,8);</lang>
plan 9;
is-approx ($_√pi)**$_, pi for 2 .. 10;</syntaxhighlight>
 
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
<lang RATFOR>
program nth
#
Line 2,735 ⟶ 3,381:
 
end
</syntaxhighlight>
</lang>
<pre>
 
Line 2,763 ⟶ 3,409:
 
=={{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 2,800 ⟶ 3,446:
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 2,845 ⟶ 3,491:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(12)
see "cube root of 5 is : " + root(3, 5, 0) + nl
Line 2,858 ⟶ 3,504:
end
return x
</syntaxhighlight>
</lang>
Output:
<pre>
cube root of 5 is : 1.709975946677
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ → a n epsilon
≪ a n / DUP
'''DO'''
SWAP DROP
a n / OVER INV n 1 - ^ * OVER n 1 - * n / +
'''UNTIL''' DUP2 - ABS epsilon < '''END'''
SWAP DROP
≫ ≫ 'NROOT' STO
|
''( a n error -- a^(1/n) ) ''
Start with x0 = x1 = a/n both in stack
Loop:
Forget x(k-1)
Calculate x(k+1)
Exit loop when x(k+1) close to xk
Forget xk
|}
{{in}}
<pre>
5 3 0.000000001 NROOT
</pre>
{{out}}
<pre>
1: 1.70997594668
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def nthroot(n, a, precision = 1e-5)
x = Float(a)
begin
Line 2,874 ⟶ 3,554:
end
 
p nthroot(5,34) # => 2.02439745849989</langsyntaxhighlight>
 
=={{header|Run BASICRust}}==
{{trans|Raku}}
<lang runbasic>print "Root 125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 ))
<syntaxhighlight lang="rust">// 20210212 Rust programming solution
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))
fn nthRoot(n: f64, A: f64) -> f64 {
print " 3rd Root of 27 Precision .00001 ";using( "#.###############", NthRoot( 3, 27, 0.00001))
 
print " 2nd Root of 2 Precision .00001 ";using( "#.###############", NthRoot( 2, 2, 0.00001))
let p = 1e-9_f64 ;
print " 10th Root of 1024 Precision .00001 ";using( "#.###############", NthRoot( 10, 1024, 0.00001))
let mut x0 = A / n ;
 
wait
loop {
let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n;
function NthRoot( root, A, precision)
if (x1-x0).abs() < (x0*p).abs() { return x1 };
x0 = A
x1 = A /root x0 = x1
}
while abs( x1 -x0) >precision
}
x0 = x1
 
x1 = x1 / 1.0 ' force float
fn main() {
x1 = (( root -1.0) *x1 +A /x1^( root -1.0)) /root
println!("{}", nthRoot(3. , 8. ));
wend
}</syntaxhighlight>
NthRoot =x1
end function
end</lang>
<pre>125th Root of 5643 Precision .001 1.071559602456735
125th Root of 5643 Precision .00001 1.071547591944771
3rd Root of 27 Precision .00001 3.000000000000001
2nd Root of 2 Precision .00001 1.414213562374690
10th Root of 1024 Precision .00001 2.000000000000000</pre>
 
=={{header|Sather}}==
{{trans|Octave}}
<langsyntaxhighlight lang="sather">class MATH is
nthroot(n:INT, a:FLT):FLT
pre n > 0
Line 2,921 ⟶ 3,593:
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|Scala}}==
Using tail recursion:
<langsyntaxhighlight Scalalang="scala">def nroot(n: Int, a: Double): Double = {
@tailrec
def rec(x0: Double) : Double = {
Line 2,940 ⟶ 3,612:
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 2,964 ⟶ 3,636:
(newline)
(display (root (expt 2 10) 10 0.001))
(newline)</langsyntaxhighlight>
Output:
2.04732932236839
Line 2,975 ⟶ 3,647:
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 2,987 ⟶ 3,659:
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 2,993 ⟶ 3,665:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func nthroot(n, a, precision=1e-5) {
var x = 1.float
var prev = 0.float
Line 3,003 ⟶ 3,675:
}
 
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,018 ⟶ 3,690:
 
{{trans|Tcl}}
<langsyntaxhighlight lang="smalltalk">Number extend [
nthRoot: n [
|x0 m x1|
Line 3,030 ⟶ 3,702:
]
]
].</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,050 ⟶ 3,722:
 
#.output(nthr(2,2))
#.output(nthroot(2,2))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,059 ⟶ 3,731:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension FloatingPoint where Self: ExpressibleByFloatLiteral {
@inlinable
public func power(_ e: Int) -> Self {
Line 3,094 ⟶ 3,766:
 
print(81.root(n: 4))
print(13.root(n: 5))</langsyntaxhighlight>
 
{{out}}
Line 3,103 ⟶ 3,775:
=={{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,118 ⟶ 3,790:
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,137 ⟶ 3,809:
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,144 ⟶ 3,816:
-+
("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,156 ⟶ 3,828:
nthroot5 34.,
nthroot5 pow(34.,5.),
nthroot10 pow(7131.5,10.)></langsyntaxhighlight>
output:
<pre>
Line 3,166 ⟶ 3,838:
</pre>
 
=={{header|VBAV (Vlang)}}==
<syntaxhighlight lang="Vlang">
{{trans|Phix}}
import math
The internal power operator "^" is used in stead of an auxiliary pow_ function and the accuracy has been reduced.
 
<lang vb>Private Function nth_root(y As Double, n As Double)
fn main() {
Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy
println("cube root of 5 is: ${math.cbrt(5)}")
Dim x As Variant: x = 1
}
Do While True
</syntaxhighlight>
d = (y / x ^ (n - 1) - x) / n
 
x = x + d
{{out}}
e = eps * x '-- absolute accuracy
<pre>
If d > -e And d < e Then
cube root of 5 is: 1.709975946676697
Exit Do
End If
Loop
Debug.Print y; n; x; y ^ (1 / n)
End Function
Public Sub main()
nth_root 1024, 10
nth_root 27, 3
nth_root 2, 2
nth_root 5642, 125
nth_root 7, 0.5
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
End Sub</lang>{{out}}
<pre> 1024 10 2 2
27 3 3 3
2 2 1,41421356237309 1,4142135623731
5642 125 1,07154759194477 1,07154759194477
7 0,5 49 49
4913 3 17 17
8 3 2 2
16 2 4 4
16 4 2 2
125 3 5 5
1000000000 3 1000 1000
1000000000 9 10 10
</pre>
 
=={{header|Wren}}==
{{trans|E}}
<langsyntaxhighlight ecmascriptlang="wren">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,229 ⟶ 3,871:
for (trio in trios) {
System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))")
}</langsyntaxhighlight>
 
{{out}}
Line 3,236 ⟶ 3,878:
1024 ^ 1/10 = 2
2 ^ 1/2 = 1.4142135623731
</pre>
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">func nthRoot(x,a){
send x^(1/a);
}{a=2};
log(nthRoot(8,3));</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func real NRoot(A, N); \Return the Nth root of A
Line 3,259 ⟶ 3,911:
RlOut(0, NRoot(27., 3.)); CrLf(0);
RlOut(0, NRoot(1024.,10.)); CrLf(0);
]</langsyntaxhighlight>
 
Output:
Line 3,268 ⟶ 3,920:
2.000000000000000
</pre>
 
=={{header|Yabasic}}==
{{trans|AWK}}
<lang Yabasic>data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0
 
do
read e, b
if e = 0 break
print "The ", e, "th root of ", b, " is ", b^(1/e), " (", nthroot(b, e), ")"
loop
 
 
sub nthroot(y, n)
local eps, x, d, e
eps = 1e-15 // relative accuracy
x = 1
repeat
d = ( y / ( x^(n-1) ) - x ) / n
x = x + d
e = eps * x // absolute accuracy
until(not(d < -e or d > e ))
return x
end sub</lang>
 
=={{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,307 ⟶ 3,933:
}
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041</langsyntaxhighlight>
 
 
29

edits