Nth root: Difference between revisions

Content deleted Content added
Ssmitch45 (talk | contribs)
Thundergnat (talk | contribs)
m syntax highlighting fixup automation
Line 10: Line 10:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>F nthroot(a, n)
<syntaxhighlight lang="11l">F nthroot(a, n)
V result = a
V result = a
V x = a / n
V x = a / n
Line 20: Line 20:
print(nthroot(34.0, 5))
print(nthroot(34.0, 5))
print(nthroot(42.0, 10))
print(nthroot(42.0, 10))
print(nthroot(5.0, 2))</lang>
print(nthroot(5.0, 2))</syntaxhighlight>


{{out}}
{{out}}
Line 33: Line 33:
The 'include' file FORMAT, to format a floating point number, can be found in:
The 'include' file FORMAT, to format a floating point number, can be found in:
[[360_Assembly_include|Include files 360 Assembly]].
[[360_Assembly_include|Include files 360 Assembly]].
<lang 360asm>* Nth root - x**(1/n) - 29/07/2018
<syntaxhighlight lang="360asm">* Nth root - x**(1/n) - 29/07/2018
NTHROOT CSECT
NTHROOT CSECT
USING NTHROOT,R13 base register
USING NTHROOT,R13 base register
Line 91: Line 91:
PG DC CL80' ' buffer
PG DC CL80' ' buffer
REGEQU
REGEQU
END NTHROOT </lang>
END NTHROOT </syntaxhighlight>
{{out}}
{{out}}
<pre> 1.414213</pre>
<pre> 1.414213</pre>
Line 97: Line 97:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program nroot64.s */
/* program nroot64.s */
Line 207: Line 207:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 217: Line 217:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
{{libheader|Action! Real Math}}
<lang Action!>INCLUDE "H6:REALMATH.ACT"
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"


PROC NthRoot(REAL POINTER a,n REAL POINTER res)
PROC NthRoot(REAL POINTER a,n REAL POINTER res)
Line 262: Line 262:
Test("7","0.5")
Test("7","0.5")
Test("12.34","56.78")
Test("12.34","56.78")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Nth_root.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Nth_root.png Screenshot from Atari 8-bit computer]
Line 275: Line 275:
=={{header|Ada}}==
=={{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>''.
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;
with Ada.Text_IO; use Ada.Text_IO;


Line 303: Line 303:
Put_Line ("5642.0 125th =" & Long_Float'Image (Long_Nth_Root (5642.0, 125)));
Put_Line ("5642.0 125th =" & Long_Float'Image (Long_Nth_Root (5642.0, 125)));
end Test_Nth_Root;
end Test_Nth_Root;
</syntaxhighlight>
</lang>
Sample output:
Sample output:
<pre>
<pre>
Line 319: 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]}}
{{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}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - missing transput, and missing extended precision}}
<lang algol68>REAL default p = 0.001;
<syntaxhighlight lang="algol68">REAL default p = 0.001;
PROC nth root = (INT n, LONG REAL a, p)LONG REAL:
PROC nth root = (INT n, LONG REAL a, p)LONG REAL:
Line 343: Line 343:
10 ROOT ( LONG 7131.5 ** 10 ),
10 ROOT ( LONG 7131.5 ** 10 ),
5 ROOT 34))
5 ROOT 34))
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 354: Line 354:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% nth root algorithm %
% nth root algorithm %
% returns the nth root of A, A must be > 0 %
% returns the nth root of A, A must be > 0 %
Line 378: Line 378:
write( nthRoot( 7131.5 ** 10, 10, 1'-5 ) );
write( nthRoot( 7131.5 ** 10, 10, 1'-5 ) );
write( nthRoot( 64, 6, 1'-5 ) );
write( nthRoot( 64, 6, 1'-5 ) );
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 387: Line 387:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program nroot.s */
/* program nroot.s */
Line 490: Line 490:
dfPrec: .double 0f1E-10 @ précision
dfPrec: .double 0f1E-10 @ précision


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
{{trans|Nim}}
{{trans|Nim}}
<lang rebol>nthRoot: function [a,n][
<syntaxhighlight lang="rebol">nthRoot: function [a,n][
N: to :floating n
N: to :floating n
result: a
result: a
Line 507: Line 507:
print nthRoot 34.0 5
print nthRoot 34.0 5
print nthRoot 42.0 10
print nthRoot 42.0 10
print nthRoot 5.0 2</lang>
print nthRoot 5.0 2</syntaxhighlight>


{{out}}
{{out}}
Line 516: Line 516:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>p := 0.000001
<syntaxhighlight lang="autohotkey">p := 0.000001


MsgBox, % nthRoot( 10, 7131.5**10, p) "`n"
MsgBox, % nthRoot( 10, 7131.5**10, p) "`n"
Line 534: Line 534:
}
}
Return, x2
Return, x2
}</lang>
}</syntaxhighlight>
Message box shows:
Message box shows:
<pre>7131.500000
<pre>7131.500000
Line 542: Line 542:


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>;AutoIt Version: 3.2.10.0
<syntaxhighlight lang="autoit">;AutoIt Version: 3.2.10.0
$A=4913
$A=4913
$n=3
$n=3
Line 567: Line 567:
EndIf
EndIf
Return nth_root_rec($A,$n,((($n-1)*$x)+($A/$x^($n-1)))/$n)
Return nth_root_rec($A,$n,((($n-1)*$x)+($A/$x^($n-1)))/$n)
EndFunc</lang>
EndFunc</syntaxhighlight>
output :
output :
<pre>20
<pre>20
Line 579: Line 579:
=={{header|AWK}}==
=={{header|AWK}}==


<lang awk>
<syntaxhighlight lang="awk">
#!/usr/bin/awk -f
#!/usr/bin/awk -f
BEGIN {
BEGIN {
Line 602: Line 602:
return x
return x
}
}
</syntaxhighlight>
</lang>


Sample output:
Sample output:
Line 620: Line 620:
This function is fairly generic MS BASIC. It could likely be used in most modern BASICs with little or no change.
This function is fairly generic MS BASIC. It could likely be used in most modern BASICs with little or no change.


<lang qbasic>FUNCTION RootX (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE) AS DOUBLE
<syntaxhighlight lang="qbasic">FUNCTION RootX (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE) AS DOUBLE
DIM tmp1 AS DOUBLE, tmp2 AS DOUBLE
DIM tmp1 AS DOUBLE, tmp2 AS DOUBLE
' Initial guess:
' Initial guess:
Line 630: Line 630:
LOOP WHILE (ABS(tmp1 - tmp2) > diffLimit)
LOOP WHILE (ABS(tmp1 - tmp2) > diffLimit)
RootX = tmp1
RootX = tmp1
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


Note that for the above to work in QBasic, the function definition needs to be changed like so:
Note that for the above to work in QBasic, the function definition needs to be changed like so:
<lang qbasic>FUNCTION RootX# (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE)</lang>
<syntaxhighlight lang="qbasic">FUNCTION RootX# (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE)</syntaxhighlight>


The function is called like so:
The function is called like so:


<lang qbasic>PRINT "The "; e; "th root of "; b; " is "; RootX(b, e, .000001)</lang>
<syntaxhighlight lang="qbasic">PRINT "The "; e; "th root of "; b; " is "; RootX(b, e, .000001)</syntaxhighlight>


Sample output:
Sample output:
Line 648: Line 648:
=={{header|Basic09}}==
=={{header|Basic09}}==
{{Works with |OS9 operating system -- RUN nth(root,number,precision)}}
{{Works with |OS9 operating system -- RUN nth(root,number,precision)}}
<syntaxhighlight lang="basic09">
<lang Basic09>
PROCEDURE nth
PROCEDURE nth
PARAM N : INTEGER; A, P : REAL
PARAM N : INTEGER; A, P : REAL
Line 662: Line 662:
PRINT "The Root is: ";TEMP1
PRINT "The Root is: ";TEMP1
END
END
</syntaxhighlight>
</lang>


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang freebasic>function nth_root(n, a)
<syntaxhighlight lang="freebasic">function nth_root(n, a)
precision = 0.0001
precision = 0.0001


Line 688: Line 688:
tmp = nth_root(n, 5643)
tmp = nth_root(n, 5643)
print n; " "; tmp; chr(9); (tmp ^ n)
print n; " "; tmp; chr(9); (tmp ^ n)
next n</lang>
next n</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> *FLOAT 64
<syntaxhighlight lang="bbcbasic"> *FLOAT 64
@% = &D0D
@% = &D0D
PRINT "Cube root of 5 is "; FNroot(3, 5, 0)
PRINT "Cube root of 5 is "; FNroot(3, 5, 0)
Line 704: Line 704:
SWAP x0, x1
SWAP x0, x1
UNTIL ABS (x0 - x1) <= d
UNTIL ABS (x0 - x1) <= d
= x0</lang>
= x0</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 712: Line 712:


=={{header|bc}}==
=={{header|bc}}==
<lang bc>/* Take the nth root of 'a' (a positive real number).
<syntaxhighlight lang="bc">/* Take the nth root of 'a' (a positive real number).
* 'n' must be an integer.
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
* Result will have 'd' digits after the decimal point.
Line 741: Line 741:
scale = o
scale = o
return(y)
return(y)
}</lang>
}</syntaxhighlight>


=={{header|BQN}}==
=={{header|BQN}}==
Line 750: Line 750:
<code>_while_</code> is a [https://mlochbaum.github.io/bqncrate/ BQNcrate] idiom used for unbounded looping here.
<code>_while_</code> is a [https://mlochbaum.github.io/bqncrate/ BQNcrate] idiom used for unbounded looping here.


<lang bqn>_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
<syntaxhighlight lang="bqn">_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Root ← √
Root ← √
Root1 ← ⋆⟜÷˜
Root1 ← ⋆⟜÷˜
Line 771: Line 771:
•Show 3 Root1 5
•Show 3 Root1 5
•Show 3 Root2 5
•Show 3 Root2 5
•Show 3 Root2 5‿1E¯16</lang>
•Show 3 Root2 5‿1E¯16</syntaxhighlight>
<lang>1.7099759466766968
<syntaxhighlight lang="text">1.7099759466766968
1.7099759466766968
1.7099759466766968
1.7099759641072136
1.7099759641072136
1.709975946676697</lang>
1.709975946676697</syntaxhighlight>


[https://mlochbaum.github.io/BQN/try.html#code=X3doaWxlXyDihpAge/CdlL3ijZ/wnZS+4oiY8J2UvV/wnZWjX/CdlL7iiJjwnZS94o2f8J2UvvCdlal9ClJvb3Qg4oaQIOKImgpSb290MSDihpAg4ouG4p+cw7fLnApSb290MiDihpAgewogIG4g8J2ViiBh4oC/cHJlYzoKICAx4oqRewogICAgcOKAv3g6CiAgICDin6gKICAgICAgeAogICAgICAoKHAgw5cgbiAtIDEpICsgYSDDtyBwIOKLhiBuIC0gMSkgw7cgbgogICAg4p+pCiAgfSBfd2hpbGVfIHsKICAgIHDigL94OgogICAgcHJlYyDiiaQgfCBwIC0geAogIH0g4p+oYSwg4oyKYcO3buKfqTsKICDwnZWoIPCdlYog8J2VqTog8J2VqCDwnZWKIPCdlanigL8xRcKvNQp9CgrigKJTaG93IDMgUm9vdCA1CuKAolNob3cgMyBSb290MSA1CuKAolNob3cgMyBSb290MiA1CuKAolNob3cgMyBSb290MiA14oC/MUXCrzE2Cgo= Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=X3doaWxlXyDihpAge/CdlL3ijZ/wnZS+4oiY8J2UvV/wnZWjX/CdlL7iiJjwnZS94o2f8J2UvvCdlal9ClJvb3Qg4oaQIOKImgpSb290MSDihpAg4ouG4p+cw7fLnApSb290MiDihpAgewogIG4g8J2ViiBh4oC/cHJlYzoKICAx4oqRewogICAgcOKAv3g6CiAgICDin6gKICAgICAgeAogICAgICAoKHAgw5cgbiAtIDEpICsgYSDDtyBwIOKLhiBuIC0gMSkgw7cgbgogICAg4p+pCiAgfSBfd2hpbGVfIHsKICAgIHDigL94OgogICAgcHJlYyDiiaQgfCBwIC0geAogIH0g4p+oYSwg4oyKYcO3buKfqTsKICDwnZWoIPCdlYog8J2VqTog8J2VqCDwnZWKIPCdlanigL8xRcKvNQp9CgrigKJTaG93IDMgUm9vdCA1CuKAolNob3cgMyBSb290MSA1CuKAolNob3cgMyBSb290MiA1CuKAolNob3cgMyBSb290MiA14oC/MUXCrzE2Cgo= Try It!]
=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat does not have floating point numbers as primitive type. Instead we have to use rational numbers. This code is not fast!
Bracmat does not have floating point numbers as primitive type. Instead we have to use rational numbers. This code is not fast!
<lang bracmat>( ( root
<syntaxhighlight lang="bracmat">( ( root
= n a d x0 x1 d2 rnd 10-d
= n a d x0 x1 d2 rnd 10-d
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
Line 808: Line 808:
& show$(2,2,100)
& show$(2,2,100)
& show$(125,5642,20)
& show$(125,5642,20)
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>1024^(1/10)=2,00000000000000000000*10E0
<pre>1024^(1/10)=2,00000000000000000000*10E0
Line 817: Line 817:
=={{header|C}}==
=={{header|C}}==
Implemented without using math library, because if we were to use <code>pow()</code>, the whole exercise wouldn't make sense.
Implemented without using math library, because if we were to use <code>pow()</code>, the whole exercise wouldn't make sense.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <float.h>
#include <float.h>


Line 851: Line 851:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Almost exactly how C works.
Almost exactly how C works.
<lang csharp>
<syntaxhighlight lang="csharp">
static void Main(string[] args)
static void Main(string[] args)
{
{
Line 877: Line 877:
return x[0];
return x[0];
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==


<lang cpp>double NthRoot(double m_nValue, double index, double guess, double pc)
<syntaxhighlight lang="cpp">double NthRoot(double m_nValue, double index, double guess, double pc)
{
{
double result = guess;
double result = guess;
Line 893: Line 893:
return result;
return result;
};
};
</syntaxhighlight>
</lang>


<lang cpp>double NthRoot(double value, double degree)
<syntaxhighlight lang="cpp">double NthRoot(double value, double degree)
{
{
return pow(value, (double)(1 / degree));
return pow(value, (double)(1 / degree));
};
};
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang clojure>
<syntaxhighlight lang="clojure">
(ns test-project-intellij.core
(ns test-project-intellij.core
(:gen-class))
(:gen-class))
Line 928: Line 928:
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion


</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol>
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. Nth-Root.
PROGRAM-ID. Nth-Root.
Line 1,031: Line 1,031:
END-PROGRAM.
END-PROGRAM.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,054: Line 1,054:
=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==


<lang coffeescript>
<syntaxhighlight lang="coffeescript">
nth_root = (A, n, precision=0.0000000000001) ->
nth_root = (A, n, precision=0.0000000000001) ->
x = 1
x = 1
Line 1,081: Line 1,081:
root = nth_root x, n
root = nth_root x, n
console.log "#{x} root #{n} = #{root} (root^#{n} = #{Math.pow root, n})"
console.log "#{x} root #{n} = #{root} (root^#{n} = #{Math.pow root, n})"
</syntaxhighlight>
</lang>
output
output
<lang>
<syntaxhighlight lang="text">
> coffee nth_root.coffee
> coffee nth_root.coffee
8 root 3 = 2 (root^3 = 8)
8 root 3 = 2 (root^3 = 8)
Line 1,096: Line 1,096:
100 root 5 = 2.5118864315095806 (root^5 = 100.0000000000001)
100 root 5 = 2.5118864315095806 (root^5 = 100.0000000000001)
100 root 10 = 1.5848931924611134 (root^10 = 99.99999999999993)
100 root 10 = 1.5848931924611134 (root^10 = 99.99999999999993)
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 1,102: Line 1,102:
This version does not check for cycles in <var>x<sub>i</sub></var> and <var>x<sub>i+1</sub></var>, but finishes when the difference between them drops below <var>ε</var>. The initial guess can be provided, but defaults to <var>n-1</var>.
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>.


<lang lisp>(defun nth-root (n a &optional (epsilon .0001) (guess (1- n)))
<syntaxhighlight lang="lisp">(defun nth-root (n a &optional (epsilon .0001) (guess (1- n)))
(assert (and (> n 1) (> a 0)))
(assert (and (> n 1) (> a 0)))
(flet ((next (x)
(flet ((next (x)
Line 1,110: Line 1,110:
(do* ((xi guess xi+1)
(do* ((xi guess xi+1)
(xi+1 (next xi) (next xi)))
(xi+1 (next xi) (next xi)))
((< (abs (- xi+1 xi)) epsilon) xi+1))))</lang>
((< (abs (- xi+1 xi)) epsilon) xi+1))))</syntaxhighlight>


<code>nth-root</code> may return rationals rather than floating point numbers, so easy checking for correctness may require coercion to floats. For instance,
<code>nth-root</code> may return rationals rather than floating point numbers, so easy checking for correctness may require coercion to floats. For instance,


<lang lisp>(let* ((r (nth-root 3 10))
<syntaxhighlight lang="lisp">(let* ((r (nth-root 3 10))
(rf (coerce r 'float)))
(rf (coerce r 'float)))
(print (* r r r ))
(print (* r r r ))
(print (* rf rf rf)))</lang>
(print (* rf rf rf)))</syntaxhighlight>


produces the following output.
produces the following output.
Line 1,125: Line 1,125:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.math;
<syntaxhighlight lang="d">import std.stdio, std.math;


real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
Line 1,137: Line 1,137:
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(6, 64));
writeln(nthroot(6, 64));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>7131.5
<pre>7131.5
Line 1,143: Line 1,143:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang delphi>
<syntaxhighlight lang="delphi">
USES
USES
Math;
Math;
Line 1,159: Line 1,159:
Result := x_p;
Result := x_p;
end;
end;
</syntaxhighlight>
</lang>


=={{header|E}}==
=={{header|E}}==
Line 1,167: Line 1,167:
(Disclaimer: This was not written by a numerics expert; there may be reasons this is a bad idea. Also, it might be that cycles are always of length 2, which would reduce the amount of calculation needed by 2/3.)
(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.)


<lang e>def nthroot(n, x) {
<syntaxhighlight lang="e">def nthroot(n, x) {
require(n > 1 && x > 0)
require(n > 1 && x > 0)
def np := n - 1
def np := n - 1
Line 1,178: Line 1,178:
}
}
return g1
return g1
}</lang>
}</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>func power x n . r .
<syntaxhighlight lang="text">func power x n . r .
r = 1
r = 1
for i range n
for i range n
Line 1,200: Line 1,200:
call nth_root x 10 r
call nth_root x 10 r
numfmt 0 4
numfmt 0 4
print r</lang>
print r</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def nth_root(n, x, precision \\ 1.0e-5) 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
f = fn(prev) -> ((n - 1) * prev + x / :math.pow(prev, (n-1))) / n end
Line 1,216: Line 1,216:
Enum.each([{2, 2}, {4, 81}, {10, 1024}, {1/2, 7}], fn {n, x} ->
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)}"
IO.puts "#{n} root of #{x} is #{RC.nth_root(n, x)}"
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,228: Line 1,228:
=={{header|Erlang}}==
=={{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>:
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>:
<lang erlang>fixed_point(F, Guess, Tolerance) ->
<syntaxhighlight lang="erlang">fixed_point(F, Guess, Tolerance) ->
fixed_point(F, Guess, Tolerance, F(Guess)).
fixed_point(F, Guess, Tolerance, F(Guess)).
fixed_point(_, Guess, Tolerance, Next) when abs(Guess - Next) < Tolerance ->
fixed_point(_, Guess, Tolerance, Next) when abs(Guess - Next) < Tolerance ->
Next;
Next;
fixed_point(F, _, Tolerance, Next) ->
fixed_point(F, _, Tolerance, Next) ->
fixed_point(F, Next, Tolerance, F(Next)).</lang>
fixed_point(F, Next, Tolerance, F(Next)).</syntaxhighlight>
The nth root function algorithm defined on the wikipedia page linked above can advantage of this:
The nth root function algorithm defined on the wikipedia page linked above can advantage of this:
<lang erlang>nth_root(N, X) -> nth_root(N, X, 1.0e-5).
<syntaxhighlight lang="erlang">nth_root(N, X) -> nth_root(N, X, 1.0e-5).
nth_root(N, X, Precision) ->
nth_root(N, X, Precision) ->
F = fun(Prev) -> ((N - 1) * Prev + X / math:pow(Prev, (N-1))) / N end,
F = fun(Prev) -> ((N - 1) * Prev + X / math:pow(Prev, (N-1))) / N end,
fixed_point(F, X, Precision).</lang>
fixed_point(F, X, Precision).</syntaxhighlight>


=={{header|Excel}}==
=={{header|Excel}}==
Line 1,244: Line 1,244:


Beside the obvious;
Beside the obvious;
<lang Excel>=A1^(1/B1)</lang>
<syntaxhighlight lang="excel">=A1^(1/B1)</syntaxhighlight>
*Cell A1 is the base.
*Cell A1 is the base.
*Cell B1 is the exponent.
*Cell B1 is the exponent.
Line 1,296: Line 1,296:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let nthroot n A =
let nthroot n A =
let rec f x =
let rec f x =
Line 1,318: Line 1,318:
printf "%A" (nthroot n A)
printf "%A" (nthroot n A)
0
0
</syntaxhighlight>
</lang>


Compiled using <em>fsc nthroot.fs</em> example output:<pre>
Compiled using <em>fsc nthroot.fs</em> example output:<pre>
Line 1,326: Line 1,326:
=={{header|Factor}}==
=={{header|Factor}}==
{{trans|Forth}}
{{trans|Forth}}
<lang factor>USING: kernel locals math math.functions prettyprint ;
<syntaxhighlight lang="factor">USING: kernel locals math math.functions prettyprint ;


:: th-root ( a n -- a^1/n )
:: th-root ( a n -- a^1/n )
Line 1,337: Line 1,337:


34 5 th-root . ! 2.024397458499888
34 5 th-root . ! 2.024397458499888
34 5 recip ^ . ! 2.024397458499888</lang>
34 5 recip ^ . ! 2.024397458499888</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: th-root { F: a F: n -- a^1/n }
<syntaxhighlight lang="forth">: th-root { F: a F: n -- a^1/n }
a
a
begin
begin
Line 1,350: Line 1,350:


34e 5e th-root f. \ 2.02439745849989
34e 5e th-root f. \ 2.02439745849989
34e 5e 1/f f** f. \ 2.02439745849989</lang>
34e 5e 1/f f** f. \ 2.02439745849989</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>program NthRootTest
<syntaxhighlight lang="fortran">program NthRootTest
implicit none
implicit none


Line 1,394: Line 1,394:
end function nthroot
end function nthroot


end program NthRootTest</lang>
end program NthRootTest</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 14-01-2019
<syntaxhighlight lang="freebasic">' version 14-01-2019
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,437: Line 1,437:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre> n 5643 ^ 1 / n nth_root ^ n
<pre> n 5643 ^ 1 / n nth_root ^ n
Line 1,454: Line 1,454:


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>window 1
<syntaxhighlight lang="futurebasic">window 1


local fn NthRoot( root as long, a as long, precision as double ) as double
local fn NthRoot( root as long, a as long, precision as double ) as double
Line 1,475: Line 1,475:
print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )
print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )


HandleEvents</lang>
HandleEvents</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,489: Line 1,489:


=={{header|Go}}==
=={{header|Go}}==
<lang go>func root(a float64, n int) float64 {
<syntaxhighlight lang="go">func root(a float64, n int) float64 {
n1 := n - 1
n1 := n - 1
n1f, rn := float64(n1), 1/float64(n)
n1f, rn := float64(n1), 1/float64(n)
Line 1,507: Line 1,507:
}
}
return x
return x
}</lang>
}</syntaxhighlight>


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.
The above version is for 64 bit wide floating point numbers. The following uses `math/big` Float to implement this same function with 256 bits of precision.
Line 1,513: Line 1,513:
''A set of wrapper functions around the somewhat muddled big math library functions is used to make the main function more readable, and also it was necessary to create a power function (Exp) as the library also lacks this function.'' '''The exponent in the limit must be at least one less than the number of bits of precision of the input value or the function will enter an infinite loop!'''
''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"
import "math/big"


Line 1,579: Line 1,579:
return x.Cmp(y) == -1
return x.Cmp(y) == -1
}
}
</syntaxhighlight>
</lang>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>import static Constants.tolerance
<syntaxhighlight lang="groovy">import static Constants.tolerance
import static java.math.RoundingMode.HALF_UP
import static java.math.RoundingMode.HALF_UP


Line 1,596: Line 1,596:
(xNew as BigDecimal).setScale(7, HALF_UP)
(xNew as BigDecimal).setScale(7, HALF_UP)
}
}
</syntaxhighlight>
</lang>


Test:
Test:
<lang groovy>class Constants {
<syntaxhighlight lang="groovy">class Constants {
static final tolerance = 0.00001
static final tolerance = 0.00001
}
}
Line 1,619: Line 1,619:
it.b, it.n, r, it.r)
it.b, it.n, r, it.r)
assert (r - it.r).abs() <= tolerance
assert (r - it.r).abs() <= tolerance
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,632: Line 1,632:


Function exits when there's no difference between two successive values.
Function exits when there's no difference between two successive values.
<lang Haskell>n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n)</lang>
<syntaxhighlight lang="haskell">n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n)</syntaxhighlight>
Use:
Use:
<pre>*Main> 2 `nthRoot` 2
<pre>*Main> 2 `nthRoot` 2
Line 1,649: Line 1,649:
Or, in applicative terms, with formatted output:
Or, in applicative terms, with formatted output:


<lang haskell>nthRoot :: Double -> Double -> Double
<syntaxhighlight lang="haskell">nthRoot :: Double -> Double -> Double
nthRoot n x =
nthRoot n x =
fst $
fst $
Line 1,676: Line 1,676:
rjust n c = drop . length <*> (replicate n c ++)
rjust n c = drop . length <*> (replicate n c ++)
in unlines $
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</lang>
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Nth roots:
<pre>Nth roots:
Line 1,685: Line 1,685:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>WRITE(Messagebox) NthRoot(5, 34)
<syntaxhighlight lang="hicest">WRITE(Messagebox) NthRoot(5, 34)
WRITE(Messagebox) NthRoot(10, 7131.5^10)
WRITE(Messagebox) NthRoot(10, 7131.5^10)


Line 1,703: Line 1,703:


WRITE(Messagebox, Name) 'Cannot solve problem for:', prec, n, A
WRITE(Messagebox, Name) 'Cannot solve problem for:', prec, n, A
END</lang>
END</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
All Icon/Unicon reals are double precision.
All Icon/Unicon reals are double precision.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
showroot(125,3)
showroot(125,3)
showroot(27,3)
showroot(27,3)
Line 1,729: Line 1,729:
end
end


link printf</lang>
link printf</syntaxhighlight>


Output:<pre>3-th root of 125 = 5.0
Output:<pre>3-th root of 125 = 5.0
Line 1,744: Line 1,744:
But, since the [[Talk:Nth_root_algorithm#Comparison_to_Non-integer_Exponentiation|talk page discourages]] using built-in facilities, here is a reimplementation, using the [[#E|E]] algorithm:
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:


<lang j> '`N X NP' =. (0 { [)`(1 { [)`(2 { [)
<syntaxhighlight lang="j"> '`N X NP' =. (0 { [)`(1 { [)`(2 { [)
iter =. N %~ (NP * ]) + X % ] ^ NP
iter =. N %~ (NP * ]) + X % ] ^ NP
nth_root =: (, , _1+[) iter^:_ f. ]
nth_root =: (, , _1+[) iter^:_ f. ]
10 nth_root 7131.5^10
10 nth_root 7131.5^10
7131.5</lang>
7131.5</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|Fortran}}
{{trans|Fortran}}
<lang java>public static double nthroot(int n, double A) {
<syntaxhighlight lang="java">public static double nthroot(int n, double A) {
return nthroot(n, A, .001);
return nthroot(n, A, .001);
}
}
Line 1,769: Line 1,769:
}
}
return x;
return x;
}</lang>
}</syntaxhighlight>
{{trans|E}}
{{trans|E}}
<lang java>public static double nthroot(int n, double x) {
<syntaxhighlight lang="java">public static double nthroot(int n, double x) {
assert (n > 1 && x > 0);
assert (n > 1 && x > 0);
int np = n - 1;
int np = n - 1;
Line 1,785: Line 1,785:
private static double iter(double g, int np, int n, double x) {
private static double iter(double g, int np, int n, double x) {
return (np * g + x / Math.pow(g, np)) / n;
return (np * g + x / Math.pow(g, np)) / n;
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Gives the ''n'':nth root of ''num'', with precision ''prec''. (''n'' defaults to 2 [e.g. sqrt], ''prec'' defaults to 12.)
Gives the ''n'':nth root of ''num'', with precision ''prec''. (''n'' defaults to 2 [e.g. sqrt], ''prec'' defaults to 12.)


<lang javascript>function nthRoot(num, nArg, precArg) {
<syntaxhighlight lang="javascript">function nthRoot(num, nArg, precArg) {
var n = nArg || 2;
var n = nArg || 2;
var prec = precArg || 12;
var prec = precArg || 12;
Line 1,800: Line 1,800:
return x;
return x;
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<lang jq># An iterative algorithm for finding: self ^ (1/n) to the given
<syntaxhighlight lang="jq"># An iterative algorithm for finding: self ^ (1/n) to the given
# absolute precision if "precision" > 0, or to within the precision
# absolute precision if "precision" > 0, or to within the precision
# allowed by IEEE 754 64-bit numbers.
# allowed by IEEE 754 64-bit numbers.
Line 1,833: Line 1,833:
else [., ., (./n), n, 0] | _iterate
else [., ., (./n), n, 0] | _iterate
end
end
;</lang>
;</syntaxhighlight>
'''Example''':
'''Example''':
Compare the results of iterative_nth_root and nth_root implemented using builtins
Compare the results of iterative_nth_root and nth_root implemented using builtins
<lang jq>def demo(x):
<syntaxhighlight lang="jq">def demo(x):
def nth_root(n): log / n | exp;
def nth_root(n): log / n | exp;
def lpad(n): tostring | (n - length) * " " + .;
def lpad(n): tostring | (n - length) * " " + .;
Line 1,845: Line 1,845:
# 5^m for various values of n:
# 5^m for various values of n:
"5^(1/ n): builtin precision=1e-10 precision=0",
"5^(1/ n): builtin precision=1e-10 precision=0",
( (1,-5,-3,-1,1,3,5,1000,10000) | demo(5))</lang>
( (1,-5,-3,-1,1,3,5,1000,10000) | demo(5))</syntaxhighlight>
{{Out}}
{{Out}}
<lang sh>$ jq -n -r -f nth_root_machine_precision.jq
<syntaxhighlight lang="sh">$ jq -n -r -f nth_root_machine_precision.jq
5^(1/ n): builtin precision=1e-10 precision=0
5^(1/ n): builtin precision=1e-10 precision=0
5^(1/ 1): 4.999999999999999 vs 5 vs 5
5^(1/ 1): 4.999999999999999 vs 5 vs 5
Line 1,858: Line 1,858:
5^(1/ 1000): 1.0016107337527294 vs 1.0016107337527294 vs 1.0016107337527294
5^(1/ 1000): 1.0016107337527294 vs 1.0016107337527294 vs 1.0016107337527294
5^(1/10000): 1.0001609567433902 vs 1.0001609567433902 vs 1.0001609567433902
5^(1/10000): 1.0001609567433902 vs 1.0001609567433902 vs 1.0001609567433902
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
Line 1,864: Line 1,864:
Julia has a built-in exponentiation function <code>A^(1 / n)</code>, but the specification calls for us to use Newton's method (which we iterate until the limits of machine precision are reached):
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):


<lang julia>function nthroot(n::Integer, r::Real)
<syntaxhighlight lang="julia">function nthroot(n::Integer, r::Real)
r < 0 || n == 0 && throw(DomainError())
r < 0 || n == 0 && throw(DomainError())
n < 0 && return 1 / nthroot(-n, r)
n < 0 && return 1 / nthroot(-n, r)
Line 1,880: Line 1,880:


@show nthroot.(-5:2:5, 5.0)
@show nthroot.(-5:2:5, 5.0)
@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))</lang>
@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))</syntaxhighlight>


{{out}}
{{out}}
Line 1,888: Line 1,888:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|E}}
{{trans|E}}
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun nthRoot(x: Double, n: Int): Double {
fun nthRoot(x: Double, n: Int): Double {
Line 1,908: Line 1,908:
for (number in numbers)
for (number in numbers)
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,919: Line 1,919:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Translation of Scheme
Translation of Scheme
<syntaxhighlight lang="scheme">
<lang Scheme>
{def root
{def root
{def good-enough? {lambda {next guess tol}
{def good-enough? {lambda {next guess tol}
Line 1,942: Line 1,942:
{root {pow 2 10} 10 0.001}
{root {pow 2 10} 10 0.001}
-> 2.000047868581671
-> 2.000047868581671
</syntaxhighlight>
</lang>


=={{header|langur}}==
=={{header|langur}}==
Line 1,949: Line 1,949:
{{works with|langur|0.8}}
{{works with|langur|0.8}}
{{trans|D}}
{{trans|D}}
<lang langur>writeln "operator"
<syntaxhighlight lang="langur">writeln "operator"
writeln( (7131.5 ^ 10) ^/ 10 )
writeln( (7131.5 ^ 10) ^/ 10 )
writeln 64 ^/ 6
writeln 64 ^/ 6
Line 1,967: Line 1,967:
writeln "calculation"
writeln "calculation"
writeln .nthroot(10, 7131.5 ^ 10, 0.001)
writeln .nthroot(10, 7131.5 ^ 10, 0.001)
writeln .nthroot(6, 64, 0.001)</lang>
writeln .nthroot(6, 64, 0.001)</syntaxhighlight>


{{out}}
{{out}}
Line 1,980: Line 1,980:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 ));
print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 ));
print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001))
print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001))
Line 2,003: Line 2,003:
end
end
</syntaxhighlight>
</lang>
First estimate is: 1.071559602191682 ... and better is: 1.071547591944771
First estimate is: 1.071559602191682 ... and better is: 1.071547591944771
125'th root of 5642 by LB's exponentiation operator is 1.071547591944767
125'th root of 5642 by LB's exponentiation operator is 1.071547591944767
Line 2,011: Line 2,011:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on nthRoot (x, root)
<syntaxhighlight lang="lingo">on nthRoot (x, root)
return power(x, 1.0/root)
return power(x, 1.0/root)
end</lang>
end</syntaxhighlight>
<lang lingo>the floatPrecision = 8 -- only about display/string cast of floats
<syntaxhighlight lang="lingo">the floatPrecision = 8 -- only about display/string cast of floats
put nthRoot(4, 4)
put nthRoot(4, 4)
-- 1.41421356</lang>
-- 1.41421356</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to about :a :b
<syntaxhighlight lang="logo">to about :a :b
output and [:a - :b < 1e-5] [:a - :b > -1e-5]
output and [:a - :b < 1e-5] [:a - :b > -1e-5]
end
end
Line 2,029: Line 2,029:
end
end


show root 5 34 ; 2.02439745849989</lang>
show root 5 34 ; 2.02439745849989</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
function nroot(root, num)
function nroot(root, num)
return num^(1/root)
return num^(1/root)
end
end
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 2,065: Line 2,065:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Function Root (a, n%, d as double=1.e-4) {
Function Root (a, n%, d as double=1.e-4) {
Line 2,090: Line 2,090:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==


The <code>root</code> command performs this task.
The <code>root</code> command performs this task.
<syntaxhighlight lang="maple">
<lang Maple>
root(1728, 3);
root(1728, 3);


Line 2,101: Line 2,101:


root(2.0, 2);
root(2.0, 2);
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,113: Line 2,113:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Root[A,n]</lang>
<syntaxhighlight lang="mathematica">Root[A,n]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function answer = nthRoot(number,root)
<syntaxhighlight lang="matlab">function answer = nthRoot(number,root)


format long
format long
Line 2,128: Line 2,128:
end
end


end</lang>
end</syntaxhighlight>


Sample Output:
Sample Output:
<lang MATLAB>>> nthRoot(2,2)
<syntaxhighlight lang="matlab">>> nthRoot(2,2)


ans =
ans =


1.414213562373095</lang>
1.414213562373095</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>nth_root(a, n) := block(
<syntaxhighlight lang="maxima">nth_root(a, n) := block(
[x, y, d, p: fpprec],
[x, y, d, p: fpprec],
fpprec: p + 10,
fpprec: p + 10,
Line 2,150: Line 2,150:
fpprec: p,
fpprec: p,
bfloat(y)
bfloat(y)
)$</lang>
)$</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Metafont does not use IEEE floating point and we can't go beyond 0.0001 or it will loop forever.
Metafont does not use IEEE floating point and we can't go beyond 0.0001 or it will loop forever.
<lang metafont>vardef mnthroot(expr n, A) =
<syntaxhighlight lang="metafont">vardef mnthroot(expr n, A) =
x0 := A / n;
x0 := A / n;
m := n - 1;
m := n - 1;
Line 2,170: Line 2,170:
show 0.5 nthroot 7; % 49.00528
show 0.5 nthroot 7; % 49.00528


bye</lang>
bye</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>1/x <-> x^y С/П</lang>
<syntaxhighlight lang="text">1/x <-> x^y С/П</syntaxhighlight>
Instruction: ''number'' ^ ''degree'' В/О С/П
Instruction: ''number'' ^ ''degree'' В/О С/П


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|REXX}}
{{trans|REXX}}
<lang netrexx>
<syntaxhighlight lang="netrexx">
/*NetRexx program to calculate the Nth root of X, with DIGS accuracy. */
/*NetRexx program to calculate the Nth root of X, with DIGS accuracy. */
class nth_root
class nth_root
Line 2,258: Line 2,258:
return _/1 /*normalize the number to digs. */
return _/1 /*normalize the number to digs. */


</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(define (nth-root n a)
<syntaxhighlight lang="newlisp">(define (nth-root n a)
(let ((x1 a)
(let ((x1 a)
(x2 (div a n)))
(x2 (div a n)))
Line 2,271: Line 2,271:
(div a (pow x1 (- n 1))))
(div a (pow x1 (- n 1))))
n)))
n)))
x2))</lang>
x2))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import math
<syntaxhighlight lang="nim">import math


proc nthRoot(a: float; n: int): float =
proc nthRoot(a: float; n: int): float =
Line 2,286: Line 2,286:
echo nthRoot(34.0, 5)
echo nthRoot(34.0, 5)
echo nthRoot(42.0, 10)
echo nthRoot(42.0, 10)
echo nthRoot(5.0, 2)</lang>
echo nthRoot(5.0, 2)</syntaxhighlight>
Output:
Output:
<pre>2.024397458499885
<pre>2.024397458499885
Line 2,294: Line 2,294:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|C}}
{{trans|C}}
<lang objeck>class NthRoot {
<syntaxhighlight lang="objeck">class NthRoot {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
NthRoot(5, 34, .001)->PrintLine();
NthRoot(5, 34, .001)->PrintLine();
Line 2,311: Line 2,311:
return x[1];
return x[1];
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
{{trans|C}}
{{trans|C}}
<lang ocaml>let nthroot ~n ~a ?(tol=0.001) () =
<syntaxhighlight lang="ocaml">let nthroot ~n ~a ?(tol=0.001) () =
let nf = float n in let nf1 = nf -. 1.0 in
let nf = float n in let nf1 = nf -. 1.0 in
let rec iter x =
let rec iter x =
Line 2,326: Line 2,326:
Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ());
Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ());
Printf.printf "%g\n" (nthroot 5 34.0 ());
Printf.printf "%g\n" (nthroot 5 34.0 ());
;;</lang>
;;</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
Octave has it's how <tt>nthroot</tt> function.
Octave has it's how <tt>nthroot</tt> function.
<lang octave>
<syntaxhighlight lang="octave">
r = A.^(1./n)
r = A.^(1./n)
</syntaxhighlight>
</lang>


Here it is another implementation (after Tcl)
Here it is another implementation (after Tcl)


{{trans|Tcl}}
{{trans|Tcl}}
<lang octave>function r = m_nthroot(n, A)
<syntaxhighlight lang="octave">function r = m_nthroot(n, A)
x0 = A / n;
x0 = A / n;
m = n - 1;
m = n - 1;
Line 2,348: Line 2,348:
x0 = x1;
x0 = x1;
endwhile
endwhile
endfunction</lang>
endfunction</syntaxhighlight>


Here is an more elegant way by computing the successive differences in an explicit way:
Here is an more elegant way by computing the successive differences in an explicit way:
<lang octave>function r = m_nthroot(n, A)
<syntaxhighlight lang="octave">function r = m_nthroot(n, A)
r = A / n;
r = A / n;
m = n - 1;
m = n - 1;
Line 2,358: Line 2,358:
r+= d;
r+= d;
until (abs(d) < abs(r * 1e-9))
until (abs(d) < abs(r * 1e-9))
endfunction</lang>
endfunction</syntaxhighlight>


Show its usage and the built-in <tt>nthroot</tt> function
Show its usage and the built-in <tt>nthroot</tt> function


<lang octave>m_nthroot(10, 7131.5 .^ 10)
<syntaxhighlight lang="octave">m_nthroot(10, 7131.5 .^ 10)
nthroot(7131.5 .^ 10, 10)
nthroot(7131.5 .^ 10, 10)
m_nthroot(5, 34)
m_nthroot(5, 34)
nthroot(34, 5)
nthroot(34, 5)
m_nthroot(0.5, 7)
m_nthroot(0.5, 7)
nthroot(7, .5)</lang>
nthroot(7, .5)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>Float method: nthroot(n)
<syntaxhighlight lang="oforth">Float method: nthroot(n)
1.0 doWhile: [ self over n 1 - pow / over - n / tuck + swap 0.0 <> ] ;</lang>
1.0 doWhile: [ self over n 1 - pow / over - n / tuck + swap 0.0 <> ] ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,387: Line 2,387:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {NthRoot NInt A}
fun {NthRoot NInt A}
N = {Int.toFloat NInt}
N = {Int.toFloat NInt}
Line 2,405: Line 2,405:
end
end
in
in
{Show {NthRoot 2 2.0}}</lang>
{Show {NthRoot 2 2.0}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>root(n,A)=A^(1/n);</lang>
<syntaxhighlight lang="parigp">root(n,A)=A^(1/n);</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 2,415: Line 2,415:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Tcl}}
{{trans|Tcl}}
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;


sub nthroot ($$)
sub nthroot ($$)
Line 2,428: Line 2,428:
$x0 = $x1;
$x0 = $x1;
}
}
}</lang>
}</syntaxhighlight>


<lang perl>print nthroot(5, 34), "\n";
<syntaxhighlight lang="perl">print nthroot(5, 34), "\n";
print nthroot(10, 7131.5 ** 10), "\n";
print nthroot(10, 7131.5 ** 10), "\n";
print nthroot(0.5, 7), "\n";</lang>
print nthroot(0.5, 7), "\n";</syntaxhighlight>


=={{header|Phix}}==
=={{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.
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.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<span style="color: #008080;">function</span> <span style="color: #000000;">pow_</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
Line 2,464: Line 2,464:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
Note that a {7,0.5} test would need to use power() instead of pow_().
Note that a {7,0.5} test would need to use power() instead of pow_().
{{out}}
{{out}}
Line 2,482: Line 2,482:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def nthroot
<syntaxhighlight lang="phixmonti">def nthroot
var n var y
var n var y
1e-15 var eps /# relative accuracy #/
1e-15 var eps /# relative accuracy #/
Line 2,508: Line 2,508:
"The " e "th root of " b " is " b 1 e / power " (" b e nthroot ")" 9 tolist
"The " e "th root of " b " is " b 1 e / power " (" b e nthroot ")" 9 tolist
printList drop nl
printList drop nl
endfor</lang>
endfor</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang PHP>function nthroot($number, $root, $p = P)
<syntaxhighlight lang="php">function nthroot($number, $root, $p = P)
{
{
$x[0] = $number;
$x[0] = $number;
Line 2,521: Line 2,521:
}
}
return $x[1];
return $x[1];
}</lang>
}</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
L = [[2,2],
L = [[2,2],
[34,5],
[34,5],
Line 2,553: Line 2,553:
X0 := X1,
X0 := X1,
X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1))))
X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1))))
while( abs(X0-X1) > Precision).</lang>
while( abs(X0-X1) > Precision).</syntaxhighlight>


{{out}}
{{out}}
Line 2,564: Line 2,564:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(load "@lib/math.l")
<syntaxhighlight lang="picolisp">(load "@lib/math.l")


(de nthRoot (N A)
(de nthRoot (N A)
Line 2,580: Line 2,580:
(prinl (format (nthRoot 2 2.0) *Scl))
(prinl (format (nthRoot 2 2.0) *Scl))
(prinl (format (nthRoot 3 12.3) *Scl))
(prinl (format (nthRoot 3 12.3) *Scl))
(prinl (format (nthRoot 4 45.6) *Scl))</lang>
(prinl (format (nthRoot 4 45.6) *Scl))</syntaxhighlight>
Output:
Output:
<pre>1.414214
<pre>1.414214
Line 2,587: Line 2,587:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>/* Finds the N-th root of the number A */
<syntaxhighlight lang="pl/i">/* Finds the N-th root of the number A */
root: procedure (A, N) returns (float);
root: procedure (A, N) returns (float);
declare A float, N fixed binary;
declare A float, N fixed binary;
Line 2,599: Line 2,599:
end;
end;
return (xi);
return (xi);
end root;</lang>
end root;</syntaxhighlight>
Results:
Results:
<pre>
<pre>
Line 2,611: Line 2,611:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
This sample implementation does not use <code>[System.Math]</code> classes.
This sample implementation does not use <code>[System.Math]</code> classes.
<lang powershell>#NoTeS: This sample code does not validate inputs
<syntaxhighlight lang="powershell">#NoTeS: This sample code does not validate inputs
# Thus, if there are errors the 'scary' red-text
# Thus, if there are errors the 'scary' red-text
# error messages will appear.
# error messages will appear.
Line 2,649: Line 2,649:


((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)-1)/2</lang>
((root 5 2)-1)/2</syntaxhighlight>
{{Out}}
{{Out}}
<pre>PS> .\NTH.PS1
<pre>PS> .\NTH.PS1
Line 2,663: Line 2,663:
=={{header|Prolog}}==
=={{header|Prolog}}==
Uses integer math, though via scaling, it can approximate non-integral roots to arbitrary precision.
Uses integer math, though via scaling, it can approximate non-integral roots to arbitrary precision.
<syntaxhighlight lang="prolog">
<lang Prolog>
iroot(_, 0, 0) :- !.
iroot(_, 0, 0) :- !.
iroot(M, N, R) :-
iroot(M, N, R) :-
Line 2,685: Line 2,685:
newton(2, A, X0, X1) :- X1 is (X0 + A div X0) >> 1, !. % fast special case
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.
newton(N, A, X0, X1) :- X1 is ((N - 1)*X0 + A div X0**(N - 1)) div N.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,710: Line 2,710:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>#Def_p=0.001
<syntaxhighlight lang="purebasic">#Def_p=0.001


Procedure.d Nth_root(n.i, A.d, p.d=#Def_p)
Procedure.d Nth_root(n.i, A.d, p.d=#Def_p)
Line 2,728: Line 2,728:
Debug Nth_root(125,5642)
Debug Nth_root(125,5642)
Debug "And better:"
Debug "And better:"
Debug Nth_root(125,5642,0.00001)</lang>
Debug Nth_root(125,5642,0.00001)</syntaxhighlight>
'''Outputs
'''Outputs
125'th root of 5642 is
125'th root of 5642 is
Line 2,738: Line 2,738:


=={{header|Python}}==
=={{header|Python}}==
<lang python>from decimal import Decimal, getcontext
<syntaxhighlight lang="python">from decimal import Decimal, getcontext


def nthroot (n, A, precision):
def nthroot (n, A, precision):
Line 2,750: Line 2,750:
x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1))))
x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1))))
if x_0 == x_1:
if x_0 == x_1:
return x_1</lang>
return x_1</syntaxhighlight>


<lang python>print nthroot(5, 34, 10)
<syntaxhighlight lang="python">print nthroot(5, 34, 10)
print nthroot(10,42, 20)
print nthroot(10,42, 20)
print nthroot(2, 5, 400)</lang>
print nthroot(2, 5, 400)</syntaxhighlight>


Or, in terms of a general '''until''' function:
Or, in terms of a general '''until''' function:
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Nth Root'''
<syntaxhighlight lang="python">'''Nth Root'''


from decimal import Decimal, getcontext
from decimal import Decimal, getcontext
Line 2,868: Line 2,868:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Nth roots at various precisions:
<pre>Nth roots at various precisions:
Line 2,877: Line 2,877:


=={{header|R}}==
=={{header|R}}==
<lang R>nthroot <- function(A, n, tol=sqrt(.Machine$double.eps))
<syntaxhighlight lang="r">nthroot <- function(A, n, tol=sqrt(.Machine$double.eps))
{
{
ifelse(A < 1, x0 <- A * n, x0 <- A / n)
ifelse(A < 1, x0 <- A * n, x0 <- A / n)
Line 2,888: Line 2,888:
}
}
nthroot(7131.5^10, 10) # 7131.5
nthroot(7131.5^10, 10) # 7131.5
nthroot(7, 0.5) # 49</lang>
nthroot(7, 0.5) # 49</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (nth-root number root (tolerance 0.001))
(define (nth-root number root (tolerance 0.001))
Line 2,905: Line 2,905:
next-guess
next-guess
(loop next-guess)))
(loop next-guess)))
(loop 1.0))</lang>
(loop 1.0))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>sub nth-root ($n, $A, $p=1e-9)
<syntaxhighlight lang="raku" line>sub nth-root ($n, $A, $p=1e-9)
{
{
my $x0 = $A / $n;
my $x0 = $A / $n;
Line 2,920: Line 2,920:
}
}


say nth-root(3,8);</lang>
say nth-root(3,8);</syntaxhighlight>


=={{header|RATFOR}}==
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
<lang RATFOR>
program nth
program nth
#
#
Line 2,959: Line 2,959:


end
end
</syntaxhighlight>
</lang>
<pre>
<pre>


Line 2,987: Line 2,987:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program calculates the Nth root of X, with DIGS (decimal digits) accuracy. */
<syntaxhighlight 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*/
parse arg x root digs . /*obtain optional arguments from the CL*/
if x=='' | x=="," then x= 2 /*Not specified? Then use the default.*/
if x=='' | x=="," then x= 2 /*Not specified? Then use the default.*/
Line 3,024: Line 3,024:
if \complex then g=g*sign(Ox) /*adjust the sign (maybe). */
if \complex then g=g*sign(Ox) /*adjust the sign (maybe). */
numeric digits oDigs /*reinstate the original digits. */
numeric digits oDigs /*reinstate the original digits. */
return (g/1) || left('j', complex) /*normalize # to digs, append j ?*/</lang>
return (g/1) || left('j', complex) /*normalize # to digs, append j ?*/</syntaxhighlight>
'''output''' &nbsp; when using the default inputs:
'''output''' &nbsp; when using the default inputs:
<pre>
<pre>
Line 3,069: Line 3,069:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
decimals(12)
decimals(12)
see "cube root of 5 is : " + root(3, 5, 0) + nl
see "cube root of 5 is : " + root(3, 5, 0) + nl
Line 3,082: Line 3,082:
end
end
return x
return x
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,089: Line 3,089:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def nthroot(n, a, precision = 1e-5)
<syntaxhighlight lang="ruby">def nthroot(n, a, precision = 1e-5)
x = Float(a)
x = Float(a)
begin
begin
Line 3,098: Line 3,098:
end
end


p nthroot(5,34) # => 2.02439745849989</lang>
p nthroot(5,34) # => 2.02439745849989</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>print "Root 125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 ))
<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 .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 ))
print "125th Root of 5643 Precision .00001 ";using( "#.###############", NthRoot( 125, 5642, 0.00001))
print "125th Root of 5643 Precision .00001 ";using( "#.###############", NthRoot( 125, 5642, 0.00001))
Line 3,121: Line 3,121:
end function
end function
end</lang>
end</syntaxhighlight>
<pre>125th Root of 5643 Precision .001 1.071559602456735
<pre>125th Root of 5643 Precision .001 1.071559602456735
125th Root of 5643 Precision .00001 1.071547591944771
125th Root of 5643 Precision .00001 1.071547591944771
Line 3,130: Line 3,130:
=={{header|Rust}}==
=={{header|Rust}}==
{{trans|Raku}}
{{trans|Raku}}
<lang rust>// 20210212 Rust programming solution
<syntaxhighlight lang="rust">// 20210212 Rust programming solution


fn nthRoot(n: f64, A: f64) -> f64 {
fn nthRoot(n: f64, A: f64) -> f64 {
Line 3,146: Line 3,146:
fn main() {
fn main() {
println!("{}", nthRoot(3. , 8. ));
println!("{}", nthRoot(3. , 8. ));
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
{{trans|Octave}}
{{trans|Octave}}
<lang sather>class MATH is
<syntaxhighlight lang="sather">class MATH is
nthroot(n:INT, a:FLT):FLT
nthroot(n:INT, a:FLT):FLT
pre n > 0
pre n > 0
Line 3,165: Line 3,165:
end;
end;


end;</lang>
end;</syntaxhighlight>


<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
main is
main is
a:FLT := 2.5 ^ 10.0;
a:FLT := 2.5 ^ 10.0;
#OUT + MATH::nthroot(10, a) + "\n";
#OUT + MATH::nthroot(10, a) + "\n";
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|S-BASIC}}==
=={{header|S-BASIC}}==
Line 3,178: Line 3,178:
seems unnecessarily cumbersome, given the ready availability of S-BASIC's built-in exp and
seems unnecessarily cumbersome, given the ready availability of S-BASIC's built-in exp and
natural log functions.
natural log functions.
<lang basic>
<syntaxhighlight lang="basic">
rem - return nth root of x
rem - return nth root of x
function nthroot(x, n = real) = real
function nthroot(x, n = real) = real
Line 3,194: Line 3,194:


end
end
</syntaxhighlight>
</lang>
But if the six or seven digits supported by S-BASIC's single-precision REAL data type is insufficient, Newton's Method is the way to go, given that the built-in exp and natural log functions are only single-precision.
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.
<lang basic>
<syntaxhighlight lang="basic">
rem - return the nth root of real.double value x to stated precision
rem - return the nth root of real.double value x to stated precision
function nthroot(n, x, precision = real.double) = real.double
function nthroot(n, x, precision = real.double) = real.double
Line 3,220: Line 3,220:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
From the second version of the program.
From the second version of the program.
Line 3,239: Line 3,239:
=={{header|Scala}}==
=={{header|Scala}}==
Using tail recursion:
Using tail recursion:
<lang Scala>def nroot(n: Int, a: Double): Double = {
<syntaxhighlight lang="scala">def nroot(n: Int, a: Double): Double = {
@tailrec
@tailrec
def rec(x0: Double) : Double = {
def rec(x0: Double) : Double = {
Line 3,247: Line 3,247:
rec(a)
rec(a)
}</lang>
}</syntaxhighlight>


Alternatively, you can implement the iteration with an iterator like so:
Alternatively, you can implement the iteration with an iterator like so:
<lang scala>def fallPrefix(itr: Iterator[Double]): Iterator[Double] = itr.sliding(2).dropWhile(p => p(0) > p(1)).map(_.head)
<syntaxhighlight 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</lang>
def nrootLazy(n: Int)(a: Double): Double = fallPrefix(Iterator.iterate(a){r => (((n - 1)*r) + (a/math.pow(r, n - 1)))/n}).next</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (root number degree tolerance)
<syntaxhighlight lang="scheme">(define (root number degree tolerance)
(define (good-enough? next guess)
(define (good-enough? next guess)
(< (abs (- next guess)) tolerance))
(< (abs (- next guess)) tolerance))
Line 3,271: Line 3,271:
(newline)
(newline)
(display (root (expt 2 10) 10 0.001))
(display (root (expt 2 10) 10 0.001))
(newline)</lang>
(newline)</syntaxhighlight>
Output:
Output:
2.04732932236839
2.04732932236839
Line 3,282: Line 3,282:
An alternate function which uses Newton's method is:
An alternate function which uses Newton's method is:


<lang seed7>const func float: nthRoot (in integer: n, in float: a) is func
<syntaxhighlight lang="seed7">const func float: nthRoot (in integer: n, in float: a) is func
result
result
var float: x1 is 0.0;
var float: x1 is 0.0;
Line 3,294: Line 3,294:
x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n);
x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n);
end while;
end while;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/math.htm#nthRoot]
Original source: [http://seed7.sourceforge.net/algorith/math.htm#nthRoot]
Line 3,300: Line 3,300:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>func nthroot(n, a, precision=1e-5) {
<syntaxhighlight lang="ruby">func nthroot(n, a, precision=1e-5) {
var x = 1.float
var x = 1.float
var prev = 0.float
var prev = 0.float
Line 3,310: Line 3,310:
}
}


say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204</lang>
say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204</syntaxhighlight>


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 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)''.


<lang ruby>func nthroot_fast(n, a, precision=1e-5) {
<syntaxhighlight lang="ruby">func nthroot_fast(n, a, precision=1e-5) {
{ a = nthroot(2, a, precision) } * int(n-1)
{ a = nthroot(2, a, precision) } * int(n-1)
a ** (2**int(n-1) / n)
a ** (2**int(n-1) / n)
}
}


say nthroot_fast(5, 34, 1e-64) # => 2.02439745849988504251081724554193741911462170107</lang>
say nthroot_fast(5, 34, 1e-64) # => 2.02439745849988504251081724554193741911462170107</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 3,325: Line 3,325:


{{trans|Tcl}}
{{trans|Tcl}}
<lang smalltalk>Number extend [
<syntaxhighlight lang="smalltalk">Number extend [
nthRoot: n [
nthRoot: n [
|x0 m x1|
|x0 m x1|
Line 3,337: Line 3,337:
]
]
]
]
].</lang>
].</syntaxhighlight>


<lang smalltalk>(34 nthRoot: 5) displayNl.
<syntaxhighlight lang="smalltalk">(34 nthRoot: 5) displayNl.
((7131.5 raisedTo: 10) nthRoot: 10) displayNl.
((7131.5 raisedTo: 10) nthRoot: 10) displayNl.
(7 nthRoot: 0.5) displayNl.</lang>
(7 nthRoot: 0.5) displayNl.</syntaxhighlight>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>nthr(n,r) <= n^(1/r)
<syntaxhighlight lang="spl">nthr(n,r) <= n^(1/r)


nthroot(n,r)=
nthroot(n,r)=
Line 3,357: Line 3,357:


#.output(nthr(2,2))
#.output(nthr(2,2))
#.output(nthroot(2,2))</lang>
#.output(nthroot(2,2))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,366: Line 3,366:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>extension FloatingPoint where Self: ExpressibleByFloatLiteral {
<syntaxhighlight lang="swift">extension FloatingPoint where Self: ExpressibleByFloatLiteral {
@inlinable
@inlinable
public func power(_ e: Int) -> Self {
public func power(_ e: Int) -> Self {
Line 3,401: Line 3,401:


print(81.root(n: 4))
print(81.root(n: 4))
print(13.root(n: 5))</lang>
print(13.root(n: 5))</syntaxhighlight>


{{out}}
{{out}}
Line 3,410: Line 3,410:
=={{header|Tcl}}==
=={{header|Tcl}}==
The easiest way is to just use the <code>pow</code> function (or exponentiation operator) like this:
The easiest way is to just use the <code>pow</code> function (or exponentiation operator) like this:
<lang tcl>proc nthroot {n A} {
<syntaxhighlight lang="tcl">proc nthroot {n A} {
expr {pow($A, 1.0/$n)}
expr {pow($A, 1.0/$n)}
}</lang>
}</syntaxhighlight>
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>
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}}
{{works with|Tcl|8.5}}
<lang tcl>proc nthroot {n A} {
<syntaxhighlight lang="tcl">proc nthroot {n A} {
set x0 [expr {$A / double($n)}]
set x0 [expr {$A / double($n)}]
set m [expr {$n - 1.0}]
set m [expr {$n - 1.0}]
Line 3,425: Line 3,425:
set x0 $x1
set x0 $x1
}
}
}</lang>
}</syntaxhighlight>
Demo:
Demo:
<lang tcl>puts [nthroot 2 2]
<syntaxhighlight lang="tcl">puts [nthroot 2 2]
puts [nthroot 5 34]
puts [nthroot 5 34]
puts [nthroot 5 [expr {34**5}]]
puts [nthroot 5 [expr {34**5}]]
puts [nthroot 10 [expr 7131.5**10]]
puts [nthroot 10 [expr 7131.5**10]]
puts [nthroot 0.5 7]; # Squaring!</lang>
puts [nthroot 0.5 7]; # Squaring!</syntaxhighlight>
Output:
Output:
<pre>1.414213562373095
<pre>1.414213562373095
Line 3,440: Line 3,440:


=={{header|True BASIC}}==
=={{header|True BASIC}}==
<lang qbasic>FUNCTION Nroot (n, a)
<syntaxhighlight lang="qbasic">FUNCTION Nroot (n, a)
LET precision = .00001
LET precision = .00001


Line 3,471: Line 3,471:
PRINT USING "####.########": (tmp ^ n)
PRINT USING "####.########": (tmp ^ n)
NEXT n
NEXT n
END</lang>
END</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 3,478: Line 3,478:
Error is on the order of machine precision because the stopping
Error is on the order of machine precision because the stopping
criterion is either a fixed point or a repeating cycle.
criterion is either a fixed point or a repeating cycle.
<lang Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat
#import flo
#import flo


Line 3,485: Line 3,485:
-+
-+
("n","n-1"). "A". ("x". div\"n" plus/times("n-1","x") div("A",pow("x","n-1")))^== 1.,
("n","n-1"). "A". ("x". div\"n" plus/times("n-1","x") div("A",pow("x","n-1")))^== 1.,
float^~/~& predecessor+-</lang>
float^~/~& predecessor+-</syntaxhighlight>
This implementation is unnecessary in practice due to the availability of the library
This implementation is unnecessary in practice due to the availability of the library
function pow, which performs exponentiation and allows fractional exponents.
function pow, which performs exponentiation and allows fractional exponents.
Here is a test program.
Here is a test program.
<lang Ursala>#cast %eL
<syntaxhighlight lang="ursala">#cast %eL


examples =
examples =
Line 3,497: Line 3,497:
nthroot5 34.,
nthroot5 34.,
nthroot5 pow(34.,5.),
nthroot5 pow(34.,5.),
nthroot10 pow(7131.5,10.)></lang>
nthroot10 pow(7131.5,10.)></syntaxhighlight>
output:
output:
<pre>
<pre>
Line 3,510: Line 3,510:
{{trans|Phix}}
{{trans|Phix}}
The internal power operator "^" is used in stead of an auxiliary pow_ function and the accuracy has been reduced.
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)
<syntaxhighlight lang="vb">Private Function nth_root(y As Double, n As Double)
Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy
Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy
Dim x As Variant: x = 1
Dim x As Variant: x = 1
Line 3,536: Line 3,536:
nth_root 1000000000, 3
nth_root 1000000000, 3
nth_root 1000000000, 9
nth_root 1000000000, 9
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 1024 10 2 2
<pre> 1024 10 2 2
27 3 3 3
27 3 3 3
Line 3,553: Line 3,553:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|E}}
{{trans|E}}
<lang ecmascript>var nthRoot = Fn.new { |x, n|
<syntaxhighlight lang="ecmascript">var nthRoot = Fn.new { |x, n|
if (n < 2) Fiber.abort("n must be more than 1")
if (n < 2) Fiber.abort("n must be more than 1")
if (x <= 0) Fiber.abort("x must be positive")
if (x <= 0) Fiber.abort("x must be positive")
Line 3,570: Line 3,570:
for (trio in trios) {
for (trio in trios) {
System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))")
System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,580: Line 3,580:


=={{header|XBS}}==
=={{header|XBS}}==
<lang XBS>func nthRoot(x,a){
<syntaxhighlight lang="xbs">func nthRoot(x,a){
send x^(1/a);
send x^(1/a);
}{a=2};
}{a=2};
log(nthRoot(8,3));</lang>
log(nthRoot(8,3));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,590: Line 3,590:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\stdlib;
<syntaxhighlight lang="xpl0">include c:\cxpl\stdlib;


func real NRoot(A, N); \Return the Nth root of A
func real NRoot(A, N); \Return the Nth root of A
Line 3,610: Line 3,610:
RlOut(0, NRoot(27., 3.)); CrLf(0);
RlOut(0, NRoot(27., 3.)); CrLf(0);
RlOut(0, NRoot(1024.,10.)); CrLf(0);
RlOut(0, NRoot(1024.,10.)); CrLf(0);
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 3,622: Line 3,622:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|AWK}}
{{trans|AWK}}
<lang Yabasic>data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0
<syntaxhighlight lang="yabasic">data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0


do
do
Line 3,644: Line 3,644:
return x
return x
end sub</lang>
end sub</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang zkl>fcn nthroot(nth,a,precision=1.0e-5){
<syntaxhighlight lang="zkl">fcn nthroot(nth,a,precision=1.0e-5){
x:=prev:=a=a.toFloat(); n1:=nth-1;
x:=prev:=a=a.toFloat(); n1:=nth-1;
do{
do{
Line 3,658: Line 3,658:
}
}
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041</lang>
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041</syntaxhighlight>