Nth root: Difference between revisions
→{{header|langur}}
Langurmonkey (talk | contribs) |
|||
(22 intermediate revisions by 14 users not shown) | |||
Line 10:
{{trans|Nim}}
<
V result = a
V x = a / n
Line 20:
print(nthroot(34.0, 5))
print(nthroot(42.0, 10))
print(nthroot(5.0, 2))</
{{out}}
Line 33:
The 'include' file FORMAT, to format a floating point number, can be found in:
[[360_Assembly_include|Include files 360 Assembly]].
<
NTHROOT CSECT
USING NTHROOT,R13 base register
Line 91:
PG DC CL80' ' buffer
REGEQU
END NTHROOT </
{{out}}
<pre> 1.414213</pre>
Line 97:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight 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>
{{Output}}
<pre>
Line 217:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
PROC NthRoot(REAL POINTER a,n REAL POINTER res)
Line 262:
Test("7","0.5")
Test("12.34","56.78")
RETURN</
{{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>''≥''x''<sub>''k''</sub>''.
<syntaxhighlight 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>
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}}
<
PROC nth root = (INT n, LONG REAL a, p)LONG REAL:
Line 343:
10 ROOT ( LONG 7131.5 ** 10 ),
5 ROOT 34))
)</
Output:
<pre>
Line 354:
=={{header|ALGOL W}}==
<
% 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.</
{{out}}
<pre>
Line 387:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program nroot.s */
Line 490:
dfPrec: .double 0f1E-10 @ précision
</syntaxhighlight>
=={{header|Arturo}}==
{{trans|Nim}}
<
N: to :floating n
result: a
Line 507:
print nthRoot 34.0 5
print nthRoot 42.0 10
print nthRoot 5.0 2</
{{out}}
Line 516:
=={{header|AutoHotkey}}==
<
MsgBox, % nthRoot( 10, 7131.5**10, p) "`n"
Line 534:
}
Return, x2
}</
Message box shows:
<pre>7131.500000
Line 542:
=={{header|AutoIt}}==
<
$A=4913
$n=3
Line 567:
EndIf
Return nth_root_rec($A,$n,((($n-1)*$x)+($A/$x^($n-1)))/$n)
EndFunc</
output :
<pre>20
Line 579:
=={{header|AWK}}==
<
#!/usr/bin/awk -f
BEGIN {
Line 602:
return x
}
</syntaxhighlight>
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.
<
DIM tmp1 AS DOUBLE, tmp2 AS DOUBLE
' Initial guess:
Line 630:
LOOP WHILE (ABS(tmp1 - tmp2) > diffLimit)
RootX = tmp1
END FUNCTION</
Note that for the above to work in QBasic, the function definition needs to be changed like so:
<
The function is called like so:
<
Sample output:
Line 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">
PROCEDURE nth
PARAM N : INTEGER; A, P : REAL
Line 662:
PRINT "The Root is: ";TEMP1
END
</syntaxhighlight>
==={{header|BASIC256}}===
<
precision = 0.0001
Line 688:
tmp = nth_root(n, 5643)
print n; " "; tmp; chr(9); (tmp ^ n)
next n</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
@% = &D0D
PRINT "Cube root of 5 is "; FNroot(3, 5, 0)
Line 704:
SWAP x0, x1
UNTIL ABS (x0 - x1) <= d
= x0</
'''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|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}}==
<
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
Line 741 ⟶ 1,181:
scale = o
return(y)
}</
=={{header|BQN}}==
Line 750 ⟶ 1,190:
<code>_while_</code> is a [https://mlochbaum.github.io/bqncrate/ BQNcrate] idiom used for unbounded looping here.
<
Root ← √
Root1 ← ⋆⟜÷˜
Line 771 ⟶ 1,211:
•Show 3 Root1 5
•Show 3 Root2 5
•Show 3 Root2 5‿1E¯16</
<syntaxhighlight lang="text">1.7099759466766968
1.7099759466766968
1.7099759641072136
1.709975946676697</
[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
<
= n a d x0 x1 d2 rnd 10-d
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
Line 808 ⟶ 1,248:
& show$(2,2,100)
& show$(125,5642,20)
)</
Output:
<pre>1024^(1/10)=2,00000000000000000000*10E0
Line 814 ⟶ 1,254:
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.
<
#include <float.h>
Line 851 ⟶ 1,349:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
Almost exactly how C works.
<
static void Main(string[] args)
{
Line 877 ⟶ 1,375:
return x[0];
}
</syntaxhighlight>
=={{header|C++}}==
<
{
double result = guess;
Line 893 ⟶ 1,391:
return result;
};
</syntaxhighlight>
<
{
return pow(value, (double)(1 / degree));
};
</syntaxhighlight>
=={{header|Clojure}}==
<
(ns test-project-intellij.core
(:gen-class))
Line 928 ⟶ 1,426:
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion
</syntaxhighlight>
=={{header|COBOL}}==
<
IDENTIFICATION DIVISION.
PROGRAM-ID. Nth-Root.
Line 1,031 ⟶ 1,529:
END-PROGRAM.
</syntaxhighlight>
{{out}}
<pre>
Line 1,054 ⟶ 1,552:
=={{header|CoffeeScript}}==
<
nth_root = (A, n, precision=0.0000000000001) ->
x = 1
Line 1,081 ⟶ 1,579:
root = nth_root x, n
console.log "#{x} root #{n} = #{root} (root^#{n} = #{Math.pow root, n})"
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee nth_root.coffee
8 root 3 = 2 (root^3 = 8)
Line 1,096 ⟶ 1,594:
100 root 5 = 2.5118864315095806 (root^5 = 100.0000000000001)
100 root 10 = 1.5848931924611134 (root^10 = 99.99999999999993)
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 1,102 ⟶ 1,600:
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>.
<
(assert (and (> n 1) (> a 0)))
(flet ((next (x)
Line 1,110 ⟶ 1,608:
(do* ((xi guess xi+1)
(xi+1 (next xi) (next xi)))
((< (abs (- xi+1 xi)) epsilon) xi+1))))</
<code>nth-root</code> may return rationals rather than floating point numbers, so easy checking for correctness may require coercion to floats. For instance,
<
(rf (coerce r 'float)))
(print (* r r r ))
(print (* rf rf rf)))</
produces the following output.
Line 1,125 ⟶ 1,623:
=={{header|D}}==
<
real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
Line 1,137 ⟶ 1,635:
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(6, 64));
}</
{{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}}==
<
USES
Math;
Line 1,159 ⟶ 1,670:
Result := x_p;
end;
</syntaxhighlight>
=={{header|E}}==
Line 1,167 ⟶ 1,678:
(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.)
<
require(n > 1 && x > 0)
def np := n - 1
Line 1,178 ⟶ 1,689:
}
return g1
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
func power
for
r *= x
.
return r
.
func nth_root x n
r = 2
repeat
d = (x / p - r) / n
r += d
until abs d < 0.0001
.
return r
.
numfmt 4 0
x = power 3.1416 10
print nth_root x 10
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Erlang}}
<
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 ⟶ 1,730:
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)</
{{out}}
Line 1,228 ⟶ 1,742:
=={{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>:
<
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)).</
The nth root function algorithm defined on the wikipedia page linked above can advantage of this:
<
nth_root(N, X, Precision) ->
F = fun(Prev) -> ((N - 1) * Prev + X / math:pow(Prev, (N-1))) / N end,
fixed_point(F, X, Precision).</
=={{header|Excel}}==
Line 1,244 ⟶ 1,758:
Beside the obvious;
<
*Cell A1 is the base.
*Cell B1 is the exponent.
Line 1,296 ⟶ 1,810:
=={{header|F_Sharp|F#}}==
<
let nthroot n A =
let rec f x =
Line 1,318 ⟶ 1,832:
printf "%A" (nthroot n A)
0
</syntaxhighlight>
Compiled using <em>fsc nthroot.fs</em> example output:<pre>
Line 1,326 ⟶ 1,840:
=={{header|Factor}}==
{{trans|Forth}}
<
:: th-root ( a n -- a^1/n )
Line 1,337 ⟶ 1,851:
34 5 th-root . ! 2.024397458499888
34 5 recip ^ . ! 2.024397458499888</
=={{header|Forth}}==
<
a
begin
Line 1,350 ⟶ 1,864:
34e 5e th-root f. \ 2.02439745849989
34e 5e 1/f f** f. \ 2.02439745849989</
=={{header|Fortran}}==
<
implicit none
Line 1,394 ⟶ 1,908:
end function nthroot
end program NthRootTest</
=={{header|Go}}==
<
n1 := n - 1
n1f, rn := float64(n1), 1/float64(n)
Line 1,509 ⟶ 1,929:
}
return x
}</
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,515 ⟶ 1,935:
''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">
import "math/big"
Line 1,581 ⟶ 2,001:
return x.Cmp(y) == -1
}
</syntaxhighlight>
=={{header|Groovy}}==
Solution:
<
import static java.math.RoundingMode.HALF_UP
Line 1,598 ⟶ 2,018:
(xNew as BigDecimal).setScale(7, HALF_UP)
}
</syntaxhighlight>
Test:
<
static final tolerance = 0.00001
}
Line 1,621 ⟶ 2,041:
it.b, it.n, r, it.r)
assert (r - it.r).abs() <= tolerance
}</
Output:
Line 1,634 ⟶ 2,054:
Function exits when there's no difference between two successive values.
<
Use:
<pre>*Main> 2 `nthRoot` 2
Line 1,651 ⟶ 2,071:
Or, in applicative terms, with formatted output:
<
nthRoot n x =
fst $
Line 1,678 ⟶ 2,098:
rjust n c = drop . length <*> (replicate n c ++)
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</
{{Out}}
<pre>Nth roots:
Line 1,687 ⟶ 2,107:
=={{header|HicEst}}==
<
WRITE(Messagebox) NthRoot(10, 7131.5^10)
Line 1,705 ⟶ 2,125:
WRITE(Messagebox, Name) 'Cannot solve problem for:', prec, n, A
END</
=={{header|Icon}} and {{header|Unicon}}==
All Icon/Unicon reals are double precision.
<
showroot(125,3)
showroot(27,3)
Line 1,731 ⟶ 2,151:
end
link printf</
Output:<pre>3-th root of 125 = 5.0
Line 1,746 ⟶ 2,166:
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:
<
iter =. N %~ (NP * ]) + X % ] ^ NP
nth_root =: (, , _1+[) iter^:_ f. ]
10 nth_root 7131.5^10
7131.5</
=={{header|Java}}==
{{trans|Fortran}}
<
return nthroot(n, A, .001);
}
Line 1,771 ⟶ 2,191:
}
return x;
}</
{{trans|E}}
<
assert (n > 1 && x > 0);
int np = n - 1;
Line 1,787 ⟶ 2,207:
private static double iter(double g, int np, int n, double x) {
return (np * g + x / Math.pow(g, np)) / n;
}</
=={{header|JavaScript}}==
Gives the ''n'':nth root of ''num'', with precision ''prec''. (''n'' defaults to 2 [e.g. sqrt], ''prec'' defaults to 12.)
<
var n = nArg || 2;
var prec = precArg || 12;
Line 1,802 ⟶ 2,222:
return x;
}</
=={{header|jq}}==
<
# absolute precision if "precision" > 0, or to within the precision
# allowed by IEEE 754 64-bit numbers.
Line 1,835 ⟶ 2,255:
else [., ., (./n), n, 0] | _iterate
end
;</
'''Example''':
Compare the results of iterative_nth_root and nth_root implemented using builtins
<
def nth_root(n): log / n | exp;
def lpad(n): tostring | (n - length) * " " + .;
Line 1,847 ⟶ 2,267:
# 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))</
{{Out}}
<
5^(1/ n): builtin precision=1e-10 precision=0
5^(1/ 1): 4.999999999999999 vs 5 vs 5
Line 1,860 ⟶ 2,280:
5^(1/ 1000): 1.0016107337527294 vs 1.0016107337527294 vs 1.0016107337527294
5^(1/10000): 1.0001609567433902 vs 1.0001609567433902 vs 1.0001609567433902
</syntaxhighlight>
=={{header|Julia}}==
Line 1,866 ⟶ 2,286:
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):
<
r < 0 || n == 0 && throw(DomainError())
n < 0 && return 1 / nthroot(-n, r)
Line 1,882 ⟶ 2,302:
@show nthroot.(-5:2:5, 5.0)
@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))</
{{out}}
Line 1,890 ⟶ 2,310:
=={{header|Kotlin}}==
{{trans|E}}
<
fun nthRoot(x: Double, n: Int): Double {
Line 1,910 ⟶ 2,330:
for (number in numbers)
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
}</
{{out}}
Line 1,921 ⟶ 2,341:
=={{header|Lambdatalk}}==
Translation of Scheme
<syntaxhighlight lang="scheme">
{def root
{def good-enough? {lambda {next guess tol}
Line 1,944 ⟶ 2,364:
{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.
{{trans|D}}
<
writeln
writeln 64 ^/ 6
writeln()
val .nthroot = fn(.n, .A, .p) {
var .x = [.A, .A / .n]
while abs(.x[2]-.x[1]) > .p {
Line 1,967 ⟶ 2,383:
}
# 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"
writeln .nthroot(10, 7131.5 ^ 10, 0.001)
writeln .nthroot(6, 64, 0.001)</
{{out}}
Line 1,976 ⟶ 2,395:
2
function
7131.5
2
</pre>
=={{header|Lingo}}==
<
return power(x, 1.0/root)
end</
<
put nthRoot(4, 4)
-- 1.41421356</
=={{header|Logo}}==
<
output and [:a - :b < 1e-5] [:a - :b > -1e-5]
end
Line 2,031 ⟶ 2,419:
end
show root 5 34 ; 2.02439745849989</
=={{header|Lua}}==
<syntaxhighlight lang="lua">
function nroot(root, num)
return num^(1/root)
end
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
Line 2,067 ⟶ 2,455:
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Function Root (a, n%, d as double=1.e-4) {
Line 2,092 ⟶ 2,480:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
The <code>root</code> command performs this task.
<syntaxhighlight lang="maple">
root(1728, 3);
Line 2,103 ⟶ 2,491:
root(2.0, 2);
</syntaxhighlight>
Output:
Line 2,115 ⟶ 2,503:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang
=={{header|MATLAB}}==
<
format long
Line 2,130 ⟶ 2,518:
end
end</
Sample Output:
<
ans =
1.414213562373095</
=={{header|Maxima}}==
<
[x, y, d, p: fpprec],
fpprec: p + 10,
Line 2,152 ⟶ 2,540:
fpprec: p,
bfloat(y)
)$</
=={{header|Metafont}}==
Metafont does not use IEEE floating point and we can't go beyond 0.0001 or it will loop forever.
<
x0 := A / n;
m := n - 1;
Line 2,172 ⟶ 2,560:
show 0.5 nthroot 7; % 49.00528
bye</
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">1/x <-> x^y С/П</
Instruction: ''number'' ^ ''degree'' В/О С/П
=={{header|NetRexx}}==
{{trans|REXX}}
<
/*NetRexx program to calculate the Nth root of X, with DIGS accuracy. */
class nth_root
Line 2,260 ⟶ 2,648:
return _/1 /*normalize the number to digs. */
</syntaxhighlight>
=={{header|NewLISP}}==
<
(let ((x1 a)
(x2 (div a n)))
Line 2,273 ⟶ 2,661:
(div a (pow x1 (- n 1))))
n)))
x2))</
=={{header|Nim}}==
<
proc nthRoot(a: float; n: int): float =
Line 2,288 ⟶ 2,676:
echo nthRoot(34.0, 5)
echo nthRoot(42.0, 10)
echo nthRoot(5.0, 2)</
Output:
<pre>2.024397458499885
1.453198460282268
2.23606797749979</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}}
<
function : Main(args : String[]) ~ Nil {
NthRoot(5, 34, .001)->PrintLine();
Line 2,313 ⟶ 2,729:
return x[1];
}
}</
=={{header|OCaml}}==
{{trans|C}}
<
let nf = float n in let nf1 = nf -. 1.0 in
let rec iter x =
Line 2,328 ⟶ 2,744:
Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ());
Printf.printf "%g\n" (nthroot 5 34.0 ());
;;</
=={{header|Octave}}==
Octave has it's how <tt>nthroot</tt> function.
<
r = A.^(1./n)
</syntaxhighlight>
Here it is another implementation (after Tcl)
{{trans|Tcl}}
<
x0 = A / n;
m = n - 1;
Line 2,350 ⟶ 2,766:
x0 = x1;
endwhile
endfunction</
Here is an more elegant way by computing the successive differences in an explicit way:
<
r = A / n;
m = n - 1;
Line 2,360 ⟶ 2,776:
r+= d;
until (abs(d) < abs(r * 1e-9))
endfunction</
Show its usage and the built-in <tt>nthroot</tt> function
<
nthroot(7131.5 .^ 10, 10)
m_nthroot(5, 34)
nthroot(34, 5)
m_nthroot(0.5, 7)
nthroot(7, .5)</
=={{header|Oforth}}==
<
1.0 doWhile: [ self over n 1 - pow / over - n / tuck + swap 0.0 <> ] ;</
{{out}}
Line 2,389 ⟶ 2,805:
=={{header|Oz}}==
<
fun {NthRoot NInt A}
N = {Int.toFloat NInt}
Line 2,407 ⟶ 2,823:
end
in
{Show {NthRoot 2 2.0}}</
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
Line 2,417 ⟶ 2,833:
=={{header|Perl}}==
{{trans|Tcl}}
<
sub nthroot ($$)
Line 2,430 ⟶ 2,846:
$x0 = $x1;
}
}</
<
print nthroot(10, 7131.5 ** 10), "\n";
print nthroot(0.5, 7), "\n";</
=={{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.
<!--<
<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,466 ⟶ 2,882:
<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>
<!--</
Note that a {7,0.5} test would need to use power() instead of pow_().
{{out}}
Line 2,484 ⟶ 2,900:
=={{header|Phixmonti}}==
<
var n var y
1e-15 var eps /# relative accuracy #/
Line 2,510 ⟶ 2,926:
"The " e "th root of " b " is " b 1 e / power " (" b e nthroot ")" 9 tolist
printList drop nl
endfor</
=={{header|PHP}}==
<
{
$x[0] = $number;
Line 2,523 ⟶ 2,939:
}
return $x[1];
}</
=={{header|Picat}}==
<
L = [[2,2],
[34,5],
Line 2,555 ⟶ 2,971:
X0 := X1,
X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1))))
while( abs(X0-X1) > Precision).</
{{out}}
Line 2,566 ⟶ 2,982:
=={{header|PicoLisp}}==
<
(de nthRoot (N A)
Line 2,582 ⟶ 2,998:
(prinl (format (nthRoot 2 2.0) *Scl))
(prinl (format (nthRoot 3 12.3) *Scl))
(prinl (format (nthRoot 4 45.6) *Scl))</
Output:
<pre>1.414214
Line 2,589 ⟶ 3,005:
=={{header|PL/I}}==
<
root: procedure (A, N) returns (float);
declare A float, N fixed binary;
Line 2,601 ⟶ 3,017:
end;
return (xi);
end root;</
Results:
<pre>
Line 2,613 ⟶ 3,029:
=={{header|PowerShell}}==
This sample implementation does not use <code>[System.Math]</code> classes.
<
# Thus, if there are errors the 'scary' red-text
# error messages will appear.
Line 2,651 ⟶ 3,067:
((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)-1)/2</
{{Out}}
<pre>PS> .\NTH.PS1
Line 2,665 ⟶ 3,081:
=={{header|Prolog}}==
Uses integer math, though via scaling, it can approximate non-integral roots to arbitrary precision.
<syntaxhighlight lang="prolog">
iroot(_, 0, 0) :- !.
iroot(M, N, R) :-
Line 2,687 ⟶ 3,103:
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>
{{Out}}
<pre>
Line 2,710 ⟶ 3,126:
X = -3.
</pre>
=={{header|Python}}==
<
def nthroot (n, A, precision):
Line 2,752 ⟶ 3,140:
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</
<
print nthroot(10,42, 20)
print nthroot(2, 5, 400)</
Or, in terms of a general '''until''' function:
{{Works with|Python|3.7}}
<
from decimal import Decimal, getcontext
Line 2,870 ⟶ 3,258:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Nth roots at various precisions:
Line 2,879 ⟶ 3,267:
=={{header|R}}==
<
{
ifelse(A < 1, x0 <- A * n, x0 <- A / n)
Line 2,890 ⟶ 3,278:
}
nthroot(7131.5^10, 10) # 7131.5
nthroot(7, 0.5) # 49</
=={{header|Racket}}==
<
(define (nth-root number root (tolerance 0.001))
Line 2,907 ⟶ 3,295:
next-guess
(loop next-guess)))
(loop 1.0))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
.tail given $A / $n, { (($n-1) * $_+ $A / ($_** ($n-1))) / $n } ... * ≅ *;
}
use Test;
plan 9;
is-approx ($_√pi)**$_, pi for 2 .. 10;</syntaxhighlight>
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
program nth
#
Line 2,961 ⟶ 3,345:
end
</syntaxhighlight>
<pre>
Line 2,989 ⟶ 3,373:
=={{header|REXX}}==
<
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,026 ⟶ 3,410:
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 ?*/</
'''output''' when using the default inputs:
<pre>
Line 3,071 ⟶ 3,455:
=={{header|Ring}}==
<
decimals(12)
see "cube root of 5 is : " + root(3, 5, 0) + nl
Line 3,084 ⟶ 3,468:
end
return x
</syntaxhighlight>
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}}==
<
x = Float(a)
begin
Line 3,100 ⟶ 3,518:
end
p nthroot(5,34) # => 2.02439745849989</
=={{header|Rust}}==
{{trans|Raku}}
<
fn nthRoot(n: f64, A: f64) -> f64 {
Line 3,148 ⟶ 3,538:
fn main() {
println!("{}", nthRoot(3. , 8. ));
}</
=={{header|Sather}}==
{{trans|Octave}}
<
nthroot(n:INT, a:FLT):FLT
pre n > 0
Line 3,167 ⟶ 3,557:
end;
end;</
<
main is
a:FLT := 2.5 ^ 10.0;
#OUT + MATH::nthroot(10, a) + "\n";
end;
end;</
=={{header|Scala}}==
Using tail recursion:
<
@tailrec
def rec(x0: Double) : Double = {
Line 3,186 ⟶ 3,576:
rec(a)
}</
Alternatively, you can implement the iteration with an iterator like so:
<
def nrootLazy(n: Int)(a: Double): Double = fallPrefix(Iterator.iterate(a){r => (((n - 1)*r) + (a/math.pow(r, n - 1)))/n}).next</
=={{header|Scheme}}==
<
(define (good-enough? next guess)
(< (abs (- next guess)) tolerance))
Line 3,210 ⟶ 3,600:
(newline)
(display (root (expt 2 10) 10 0.001))
(newline)</
Output:
2.04732932236839
Line 3,221 ⟶ 3,611:
An alternate function which uses Newton's method is:
<
result
var float: x1 is 0.0;
Line 3,233 ⟶ 3,623:
x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n);
end while;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#nthRoot]
Line 3,239 ⟶ 3,629:
=={{header|Sidef}}==
{{trans|Ruby}}
<
var x = 1.float
var prev = 0.float
Line 3,249 ⟶ 3,639:
}
say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204</
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)''.
<
{ a = nthroot(2, a, precision) } * int(n-1)
a ** (2**int(n-1) / n)
}
say nthroot_fast(5, 34, 1e-64) # => 2.02439745849988504251081724554193741911462170107</
=={{header|Smalltalk}}==
Line 3,264 ⟶ 3,654:
{{trans|Tcl}}
<
nthRoot: n [
|x0 m x1|
Line 3,276 ⟶ 3,666:
]
]
].</
<
((7131.5 raisedTo: 10) nthRoot: 10) displayNl.
(7 nthRoot: 0.5) displayNl.</
=={{header|SPL}}==
<
nthroot(n,r)=
Line 3,296 ⟶ 3,686:
#.output(nthr(2,2))
#.output(nthroot(2,2))</
{{out}}
<pre>
Line 3,305 ⟶ 3,695:
=={{header|Swift}}==
<
@inlinable
public func power(_ e: Int) -> Self {
Line 3,340 ⟶ 3,730:
print(81.root(n: 4))
print(13.root(n: 5))</
{{out}}
Line 3,349 ⟶ 3,739:
=={{header|Tcl}}==
The easiest way is to just use the <code>pow</code> function (or exponentiation operator) like this:
<
expr {pow($A, 1.0/$n)}
}</
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}}
<
set x0 [expr {$A / double($n)}]
set m [expr {$n - 1.0}]
Line 3,364 ⟶ 3,754:
set x0 $x1
}
}</
Demo:
<
puts [nthroot 5 34]
puts [nthroot 5 [expr {34**5}]]
puts [nthroot 10 [expr 7131.5**10]]
puts [nthroot 0.5 7]; # Squaring!</
Output:
<pre>1.414213562373095
Line 3,377 ⟶ 3,767:
7131.5
49.0</pre>
=={{header|Ursala}}==
Line 3,417 ⟶ 3,773:
Error is on the order of machine precision because the stopping
criterion is either a fixed point or a repeating cycle.
<
#import flo
Line 3,424 ⟶ 3,780:
-+
("n","n-1"). "A". ("x". div\"n" plus/times("n-1","x") div("A",pow("x","n-1")))^== 1.,
float^~/~& predecessor+-</
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.
<
examples =
Line 3,436 ⟶ 3,792:
nthroot5 34.,
nthroot5 pow(34.,5.),
nthroot10 pow(7131.5,10.)></
output:
<pre>
Line 3,446 ⟶ 3,802:
</pre>
=={{header|
<syntaxhighlight lang="Vlang">
import math
fn main() {
println("cube root of 5 is: ${math.cbrt(5)}")
}
</syntaxhighlight>
{{out}}
<pre>
cube root of 5 is: 1.709975946676697
</pre>
=={{header|Wren}}==
{{trans|E}}
<
if (n < 2) Fiber.abort("n must be more than 1")
if (x <= 0) Fiber.abort("x must be positive")
Line 3,509 ⟶ 3,835:
for (trio in trios) {
System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))")
}</
{{out}}
Line 3,519 ⟶ 3,845:
=={{header|XBS}}==
<
send x^(1/a);
}{a=2};
log(nthRoot(8,3));</
{{out}}
<pre>
Line 3,529 ⟶ 3,855:
=={{header|XPL0}}==
<
func real NRoot(A, N); \Return the Nth root of A
Line 3,549 ⟶ 3,875:
RlOut(0, NRoot(27., 3.)); CrLf(0);
RlOut(0, NRoot(1024.,10.)); CrLf(0);
]</
Output:
Line 3,558 ⟶ 3,884:
2.000000000000000
</pre>
=={{header|zkl}}==
{{trans|Ruby}}
<
x:=prev:=a=a.toFloat(); n1:=nth-1;
do{
Line 3,597 ⟶ 3,897:
}
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041</
|