September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -0,0 +1,30 @@
/* Take the nth root of 'a' (a positive real number).
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
*/
define r(a, n, d) {
auto e, o, x, y, z
if (n == 0) return(1)
if (a == 0) return(0)
o = scale
scale = d
e = 1 / 10 ^ d
if (n < 0) {
n = -n
a = 1 / a
}
x = 1
while (1) {
y = ((n - 1) * x + a / x ^ (n - 1)) / n
z = x - y
if (z < 0) z = -z
if (z < e) break
x = y
}
scale = o
return(y)
}

View file

@ -0,0 +1,21 @@
// version 1.0.6
fun nthRoot(x: Double, n: Int): Double {
if (n < 2) throw IllegalArgumentException("n must be more than 1")
if (x <= 0.0) throw IllegalArgumentException("x must be positive")
val np = n - 1
fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n
var g1 = x
var g2 = iter(g1)
while (g1 != g2) {
g1 = iter(g1)
g2 = iter(iter(g2))
}
return g1
}
fun main(args: Array<String>) {
val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2)
for (number in numbers)
println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}")
}

View file

@ -1,3 +1,3 @@
function nth_root(num,root)
function nroot(root, num)
return num^(1/root)
end

View file

@ -0,0 +1,33 @@
function pow_(atom x, integer e)
atom r = 1
for i=1 to e do
r *= x
end for
return r
end function
function nth_root(atom y,n)
atom eps = 1e-15 -- relative accuracy
atom x = 1
while 1 do
-- atom d = ( y / power(x,n-1) - x ) / n
atom d = ( y / pow_(x,n-1) - x ) / n
x += d
atom e = eps*x -- absolute accuracy
if d > -e and d < e then exit end if
end while
return {y,n,x,power(y,1/n)}
end function
?nth_root(1024,10)
?nth_root(27,3)
?nth_root(2,2)
?nth_root(5642,125)
--?nth_root(7,0.5) -- needs power(), not pow_()
?nth_root(4913,3)
?nth_root(8,3)
?nth_root(16,2)
?nth_root(16,4)
?nth_root(125,3)
?nth_root(1000000000,3)
?nth_root(1000000000,9)

View file

@ -0,0 +1,14 @@
nthr(n,r) <= n^(1/r)
nthroot(n,r)=
a = n/r
g = n
> g!=a
g = a
a = (1/r)*(((r-1)*g)+(n/(g^(r-1))))
<
<= a
.
#.output(nthr(2,2))
#.output(nthroot(2,2))

View file

@ -0,0 +1,11 @@
fcn nthroot(nth,a,precision=1.0e-5){
x:=prev:=a=a.toFloat(); n1:=nth-1;
do{
prev=x;
x=( prev*n1 + a/prev.pow(n1) ) / nth;
}
while( not prev.closeTo(x,precision) );
x
}
nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041