Nth root: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
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 648:
=={{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>
Line 712:
=={{header|bc}}==
<
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
Line 741:
scale = o
return(y)
}</
=={{header|BQN}}==
Line 750:
<code>_while_</code> is a [https://mlochbaum.github.io/bqncrate/ BQNcrate] idiom used for unbounded looping here.
<
Root ← √
Root1 ← ⋆⟜÷˜
Line 771:
•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}}==
Bracmat does not have floating point numbers as primitive type. Instead we have to use rational numbers. This code is not fast!
<
= n a d x0 x1 d2 rnd 10-d
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
Line 808:
& show$(2,2,100)
& show$(125,5642,20)
)</
Output:
<pre>1024^(1/10)=2,00000000000000000000*10E0
Line 817:
=={{header|C}}==
Implemented without using math library, because if we were to use <code>pow()</code>, the whole exercise wouldn't make sense.
<
#include <float.h>
Line 851:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
Almost exactly how C works.
<
static void Main(string[] args)
{
Line 877:
return x[0];
}
</syntaxhighlight>
=={{header|C++}}==
<
{
double result = guess;
Line 893:
return result;
};
</syntaxhighlight>
<
{
return pow(value, (double)(1 / degree));
};
</syntaxhighlight>
=={{header|Clojure}}==
<
(ns test-project-intellij.core
(:gen-class))
Line 928:
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion
</syntaxhighlight>
=={{header|COBOL}}==
<
IDENTIFICATION DIVISION.
PROGRAM-ID. Nth-Root.
Line 1,031:
END-PROGRAM.
</syntaxhighlight>
{{out}}
<pre>
Line 1,054:
=={{header|CoffeeScript}}==
<
nth_root = (A, n, precision=0.0000000000001) ->
x = 1
Line 1,081:
root = nth_root x, n
console.log "#{x} root #{n} = #{root} (root^#{n} = #{Math.pow root, n})"
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee nth_root.coffee
8 root 3 = 2 (root^3 = 8)
Line 1,096:
100 root 5 = 2.5118864315095806 (root^5 = 100.0000000000001)
100 root 10 = 1.5848931924611134 (root^10 = 99.99999999999993)
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 1,102:
This version does not check for cycles in <var>x<sub>i</sub></var> and <var>x<sub>i+1</sub></var>, but finishes when the difference between them drops below <var>ε</var>. The initial guess can be provided, but defaults to <var>n-1</var>.
<
(assert (and (> n 1) (> a 0)))
(flet ((next (x)
Line 1,110:
(do* ((xi guess xi+1)
(xi+1 (next xi) (next xi)))
((< (abs (- xi+1 xi)) epsilon) xi+1))))</
<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:
=={{header|D}}==
<
real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
Line 1,137:
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(6, 64));
}</
{{out}}
<pre>7131.5
Line 1,143:
=={{header|Delphi}}==
<
USES
Math;
Line 1,159:
Result := x_p;
end;
</syntaxhighlight>
=={{header|E}}==
Line 1,167:
(Disclaimer: This was not written by a numerics expert; there may be reasons this is a bad idea. Also, it might be that cycles are always of length 2, which would reduce the amount of calculation needed by 2/3.)
<
require(n > 1 && x > 0)
def np := n - 1
Line 1,178:
}
return g1
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">func power x n . r .
r = 1
for i range n
Line 1,200:
call nth_root x 10 r
numfmt 0 4
print r</
=={{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:
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:
=={{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:
Beside the obvious;
<
*Cell A1 is the base.
*Cell B1 is the exponent.
Line 1,296:
=={{header|F_Sharp|F#}}==
<
let nthroot n A =
let rec f x =
Line 1,318:
printf "%A" (nthroot n A)
0
</syntaxhighlight>
Compiled using <em>fsc nthroot.fs</em> example output:<pre>
Line 1,326:
=={{header|Factor}}==
{{trans|Forth}}
<
:: th-root ( a n -- a^1/n )
Line 1,337:
34 5 th-root . ! 2.024397458499888
34 5 recip ^ . ! 2.024397458499888</
=={{header|Forth}}==
<
a
begin
Line 1,350:
34e 5e th-root f. \ 2.02439745849989
34e 5e 1/f f** f. \ 2.02439745849989</
=={{header|Fortran}}==
<
implicit none
Line 1,394:
end function nthroot
end program NthRootTest</
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,437:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre> n 5643 ^ 1 / n nth_root ^ n
Line 1,454:
=={{header|FutureBasic}}==
<
local fn NthRoot( root as long, a as long, precision as double ) as double
Line 1,475:
print " 5th Root of 34 Precision .00001", using "#.###############"; fn NthRoot( 5, 34, 0.00001 )
HandleEvents</
Output:
<pre>
Line 1,489:
=={{header|Go}}==
<
n1 := n - 1
n1f, rn := float64(n1), 1/float64(n)
Line 1,507:
}
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,513:
''A set of wrapper functions around the somewhat muddled big math library functions is used to make the main function more readable, and also it was necessary to create a power function (Exp) as the library also lacks this function.'' '''The exponent in the limit must be at least one less than the number of bits of precision of the input value or the function will enter an infinite loop!'''
<syntaxhighlight lang="go">
import "math/big"
Line 1,579:
return x.Cmp(y) == -1
}
</syntaxhighlight>
=={{header|Groovy}}==
Solution:
<
import static java.math.RoundingMode.HALF_UP
Line 1,596:
(xNew as BigDecimal).setScale(7, HALF_UP)
}
</syntaxhighlight>
Test:
<
static final tolerance = 0.00001
}
Line 1,619:
it.b, it.n, r, it.r)
assert (r - it.r).abs() <= tolerance
}</
Output:
Line 1,632:
Function exits when there's no difference between two successive values.
<
Use:
<pre>*Main> 2 `nthRoot` 2
Line 1,649:
Or, in applicative terms, with formatted output:
<
nthRoot n x =
fst $
Line 1,676:
rjust n c = drop . length <*> (replicate n c ++)
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</
{{Out}}
<pre>Nth roots:
Line 1,685:
=={{header|HicEst}}==
<
WRITE(Messagebox) NthRoot(10, 7131.5^10)
Line 1,703:
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,729:
end
link printf</
Output:<pre>3-th root of 125 = 5.0
Line 1,744:
But, since the [[Talk:Nth_root_algorithm#Comparison_to_Non-integer_Exponentiation|talk page discourages]] using built-in facilities, here is a reimplementation, using the [[#E|E]] algorithm:
<
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,769:
}
return x;
}</
{{trans|E}}
<
assert (n > 1 && x > 0);
int np = n - 1;
Line 1,785:
private static double iter(double g, int np, int n, double x) {
return (np * g + x / Math.pow(g, np)) / n;
}</
=={{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,800:
return x;
}</
=={{header|jq}}==
<
# absolute precision if "precision" > 0, or to within the precision
# allowed by IEEE 754 64-bit numbers.
Line 1,833:
else [., ., (./n), n, 0] | _iterate
end
;</
'''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,845:
# 5^m for various values of n:
"5^(1/ n): builtin precision=1e-10 precision=0",
( (1,-5,-3,-1,1,3,5,1000,10000) | demo(5))</
{{Out}}
<
5^(1/ n): builtin precision=1e-10 precision=0
5^(1/ 1): 4.999999999999999 vs 5 vs 5
Line 1,858:
5^(1/ 1000): 1.0016107337527294 vs 1.0016107337527294 vs 1.0016107337527294
5^(1/10000): 1.0001609567433902 vs 1.0001609567433902 vs 1.0001609567433902
</syntaxhighlight>
=={{header|Julia}}==
Line 1,864:
Julia has a built-in exponentiation function <code>A^(1 / n)</code>, but the specification calls for us to use Newton's method (which we iterate until the limits of machine precision are reached):
<
r < 0 || n == 0 && throw(DomainError())
n < 0 && return 1 / nthroot(-n, r)
Line 1,880:
@show nthroot.(-5:2:5, 5.0)
@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5))</
{{out}}
Line 1,888:
=={{header|Kotlin}}==
{{trans|E}}
<
fun nthRoot(x: Double, n: Int): Double {
Line 1,908:
for (number in numbers)
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
}</
{{out}}
Line 1,919:
=={{header|Lambdatalk}}==
Translation of Scheme
<syntaxhighlight lang="scheme">
{def root
{def good-enough? {lambda {next guess tol}
Line 1,942:
{root {pow 2 10} 10 0.001}
-> 2.000047868581671
</syntaxhighlight>
=={{header|langur}}==
Line 1,949:
{{works with|langur|0.8}}
{{trans|D}}
<
writeln( (7131.5 ^ 10) ^/ 10 )
writeln 64 ^/ 6
Line 1,967:
writeln "calculation"
writeln .nthroot(10, 7131.5 ^ 10, 0.001)
writeln .nthroot(6, 64, 0.001)</
{{out}}
Line 1,980:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
print "First estimate is: ", using( "#.###############", NthRoot( 125, 5642, 0.001 ));
print " ... and better is: ", using( "#.###############", NthRoot( 125, 5642, 0.00001))
Line 2,003:
end
</syntaxhighlight>
First estimate is: 1.071559602191682 ... and better is: 1.071547591944771
125'th root of 5642 by LB's exponentiation operator is 1.071547591944767
Line 2,011:
=={{header|Lingo}}==
<
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,029:
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,065:
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Function Root (a, n%, d as double=1.e-4) {
Line 2,090:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
The <code>root</code> command performs this task.
<syntaxhighlight lang="maple">
root(1728, 3);
Line 2,101:
root(2.0, 2);
</syntaxhighlight>
Output:
Line 2,113:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang
=={{header|MATLAB}}==
<
format long
Line 2,128:
end
end</
Sample Output:
<
ans =
1.414213562373095</
=={{header|Maxima}}==
<
[x, y, d, p: fpprec],
fpprec: p + 10,
Line 2,150:
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,170:
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,258:
return _/1 /*normalize the number to digs. */
</syntaxhighlight>
=={{header|NewLISP}}==
<
(let ((x1 a)
(x2 (div a n)))
Line 2,271:
(div a (pow x1 (- n 1))))
n)))
x2))</
=={{header|Nim}}==
<
proc nthRoot(a: float; n: int): float =
Line 2,286:
echo nthRoot(34.0, 5)
echo nthRoot(42.0, 10)
echo nthRoot(5.0, 2)</
Output:
<pre>2.024397458499885
Line 2,294:
=={{header|Objeck}}==
{{trans|C}}
<
function : Main(args : String[]) ~ Nil {
NthRoot(5, 34, .001)->PrintLine();
Line 2,311:
return x[1];
}
}</
=={{header|OCaml}}==
{{trans|C}}
<
let nf = float n in let nf1 = nf -. 1.0 in
let rec iter x =
Line 2,326:
Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ());
Printf.printf "%g\n" (nthroot 5 34.0 ());
;;</
=={{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,348:
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,358:
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,387:
=={{header|Oz}}==
<
fun {NthRoot NInt A}
N = {Int.toFloat NInt}
Line 2,405:
end
in
{Show {NthRoot 2 2.0}}</
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
Line 2,415:
=={{header|Perl}}==
{{trans|Tcl}}
<
sub nthroot ($$)
Line 2,428:
$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,464:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1024</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">27</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5642</span><span style="color: #0000FF;">,</span><span style="color: #000000;">125</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4913</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">125</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1000000000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">1000000000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">}},</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span>
<!--</
Note that a {7,0.5} test would need to use power() instead of pow_().
{{out}}
Line 2,482:
=={{header|Phixmonti}}==
<
var n var y
1e-15 var eps /# relative accuracy #/
Line 2,508:
"The " e "th root of " b " is " b 1 e / power " (" b e nthroot ")" 9 tolist
printList drop nl
endfor</
=={{header|PHP}}==
<
{
$x[0] = $number;
Line 2,521:
}
return $x[1];
}</
=={{header|Picat}}==
<
L = [[2,2],
[34,5],
Line 2,553:
X0 := X1,
X1 := (1.0 / NF)*((NF - 1.0)*X0 + (A / (X0 ** (NF - 1))))
while( abs(X0-X1) > Precision).</
{{out}}
Line 2,564:
=={{header|PicoLisp}}==
<
(de nthRoot (N A)
Line 2,580:
(prinl (format (nthRoot 2 2.0) *Scl))
(prinl (format (nthRoot 3 12.3) *Scl))
(prinl (format (nthRoot 4 45.6) *Scl))</
Output:
<pre>1.414214
Line 2,587:
=={{header|PL/I}}==
<
root: procedure (A, N) returns (float);
declare A float, N fixed binary;
Line 2,599:
end;
return (xi);
end root;</
Results:
<pre>
Line 2,611:
=={{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,649:
((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)-1)/2</
{{Out}}
<pre>PS> .\NTH.PS1
Line 2,663:
=={{header|Prolog}}==
Uses integer math, though via scaling, it can approximate non-integral roots to arbitrary precision.
<syntaxhighlight lang="prolog">
iroot(_, 0, 0) :- !.
iroot(M, N, R) :-
Line 2,685:
newton(2, A, X0, X1) :- X1 is (X0 + A div X0) >> 1, !. % fast special case
newton(N, A, X0, X1) :- X1 is ((N - 1)*X0 + A div X0**(N - 1)) div N.
</syntaxhighlight>
{{Out}}
<pre>
Line 2,710:
=={{header|PureBasic}}==
<
Procedure.d Nth_root(n.i, A.d, p.d=#Def_p)
Line 2,728:
Debug Nth_root(125,5642)
Debug "And better:"
Debug Nth_root(125,5642,0.00001)</
'''Outputs
125'th root of 5642 is
Line 2,738:
=={{header|Python}}==
<
def nthroot (n, A, precision):
Line 2,750:
x_0, x_1 = x_1, (1 / n)*((n - 1)*x_0 + (A / (x_0 ** (n - 1))))
if x_0 == x_1:
return x_1</
<
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,868:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Nth roots at various precisions:
Line 2,877:
=={{header|R}}==
<
{
ifelse(A < 1, x0 <- A * n, x0 <- A / n)
Line 2,888:
}
nthroot(7131.5^10, 10) # 7131.5
nthroot(7, 0.5) # 49</
=={{header|Racket}}==
<
(define (nth-root number root (tolerance 0.001))
Line 2,905:
next-guess
(loop next-guess)))
(loop 1.0))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
{
my $x0 = $A / $n;
Line 2,920:
}
say nth-root(3,8);</
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
program nth
#
Line 2,959:
end
</syntaxhighlight>
<pre>
Line 2,987:
=={{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,024:
if \complex then g=g*sign(Ox) /*adjust the sign (maybe). */
numeric digits oDigs /*reinstate the original digits. */
return (g/1) || left('j', complex) /*normalize # to digs, append j ?*/</
'''output''' when using the default inputs:
<pre>
Line 3,069:
=={{header|Ring}}==
<
decimals(12)
see "cube root of 5 is : " + root(3, 5, 0) + nl
Line 3,082:
end
return x
</syntaxhighlight>
Output:
<pre>
Line 3,089:
=={{header|Ruby}}==
<
x = Float(a)
begin
Line 3,098:
end
p nthroot(5,34) # => 2.02439745849989</
=={{header|Run BASIC}}==
<
print "125th Root of 5643 Precision .001 ";using( "#.###############", NthRoot( 125, 5642, 0.001 ))
print "125th Root of 5643 Precision .00001 ";using( "#.###############", NthRoot( 125, 5642, 0.00001))
Line 3,121:
end function
end</
<pre>125th Root of 5643 Precision .001 1.071559602456735
125th Root of 5643 Precision .00001 1.071547591944771
Line 3,130:
=={{header|Rust}}==
{{trans|Raku}}
<
fn nthRoot(n: f64, A: f64) -> f64 {
Line 3,146:
fn main() {
println!("{}", nthRoot(3. , 8. ));
}</
=={{header|Sather}}==
{{trans|Octave}}
<
nthroot(n:INT, a:FLT):FLT
pre n > 0
Line 3,165:
end;
end;</
<
main is
a:FLT := 2.5 ^ 10.0;
#OUT + MATH::nthroot(10, a) + "\n";
end;
end;</
=={{header|S-BASIC}}==
Line 3,178:
seems unnecessarily cumbersome, given the ready availability of S-BASIC's built-in exp and
natural log functions.
<
rem - return nth root of x
function nthroot(x, n = real) = real
Line 3,194:
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.
<
rem - return the nth root of real.double value x to stated precision
function nthroot(n, x, precision = real.double) = real.double
Line 3,220:
end
</syntaxhighlight>
{{out}}
From the second version of the program.
Line 3,239:
=={{header|Scala}}==
Using tail recursion:
<
@tailrec
def rec(x0: Double) : Double = {
Line 3,247:
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,271:
(newline)
(display (root (expt 2 10) 10 0.001))
(newline)</
Output:
2.04732932236839
Line 3,282:
An alternate function which uses Newton's method is:
<
result
var float: x1 is 0.0;
Line 3,294:
x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n);
end while;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#nthRoot]
Line 3,300:
=={{header|Sidef}}==
{{trans|Ruby}}
<
var x = 1.float
var prev = 0.float
Line 3,310:
}
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,325:
{{trans|Tcl}}
<
nthRoot: n [
|x0 m x1|
Line 3,337:
]
]
].</
<
((7131.5 raisedTo: 10) nthRoot: 10) displayNl.
(7 nthRoot: 0.5) displayNl.</
=={{header|SPL}}==
<
nthroot(n,r)=
Line 3,357:
#.output(nthr(2,2))
#.output(nthroot(2,2))</
{{out}}
<pre>
Line 3,366:
=={{header|Swift}}==
<
@inlinable
public func power(_ e: Int) -> Self {
Line 3,401:
print(81.root(n: 4))
print(13.root(n: 5))</
{{out}}
Line 3,410:
=={{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,425:
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,440:
=={{header|True BASIC}}==
<
LET precision = .00001
Line 3,471:
PRINT USING "####.########": (tmp ^ n)
NEXT n
END</
=={{header|Ursala}}==
Line 3,478:
Error is on the order of machine precision because the stopping
criterion is either a fixed point or a repeating cycle.
<
#import flo
Line 3,485:
-+
("n","n-1"). "A". ("x". div\"n" plus/times("n-1","x") div("A",pow("x","n-1")))^== 1.,
float^~/~& predecessor+-</
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,497:
nthroot5 34.,
nthroot5 pow(34.,5.),
nthroot10 pow(7131.5,10.)></
output:
<pre>
Line 3,510:
{{trans|Phix}}
The internal power operator "^" is used in stead of an auxiliary pow_ function and the accuracy has been reduced.
<
Dim eps As Double: eps = 0.00000000000001 '-- relative accuracy
Dim x As Variant: x = 1
Line 3,536:
nth_root 1000000000, 3
nth_root 1000000000, 9
End Sub</
<pre> 1024 10 2 2
27 3 3 3
Line 3,553:
=={{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,570:
for (trio in trios) {
System.print("%(trio[0]) ^ 1/%(trio[1])%(" "*trio[2]) = %(nthRoot.call(trio[0], trio[1]))")
}</
{{out}}
Line 3,580:
=={{header|XBS}}==
<
send x^(1/a);
}{a=2};
log(nthRoot(8,3));</
{{out}}
<pre>
Line 3,590:
=={{header|XPL0}}==
<
func real NRoot(A, N); \Return the Nth root of A
Line 3,610:
RlOut(0, NRoot(27., 3.)); CrLf(0);
RlOut(0, NRoot(1024.,10.)); CrLf(0);
]</
Output:
Line 3,622:
=={{header|Yabasic}}==
{{trans|AWK}}
<
do
Line 3,644:
return x
end sub</
=={{header|zkl}}==
{{trans|Ruby}}
<
x:=prev:=a=a.toFloat(); n1:=nth-1;
do{
Line 3,658:
}
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041</
|