Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -0,0 +1,29 @@
( ( root
= n a d x0 x1 d2 rnd 10-d
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
= N r
. !arg:(?N.?r)
& div$(!N*!r+1/2.1)*!r^-1
)
& !arg:(?n,?a,?d)
& !a*!n^-1:?x0
& 10^(-1*!d):?10-d
& whl
' ( ( rnd$(((!n+-1)*!x0+!a*!x0^(1+-1*!n))*!n^-1.10^!d)
. !x0
)
: (?x0.?x1)
& (!x0+-1*!x1)^2:~<!10-d { Exit loop when required precision is reached. }
)
& flt$(!x0,!d) { Convert rational number to floating point representation. }
)
& ( show
= N A precision
. !arg:(?N,?A,?precision)
& out$(str$(!A "^(" !N^-1 ")=" root$(!N,!A,!precision)))
)
& show$(10,1024,20)
& show$(3,27,20)
& show$(2,2,100)
& show$(125,5642,20)
)

View file

@ -0,0 +1,13 @@
defmodule RC do
def nth_root(n, x, precision \\ 1.0e-5) do
f = fn(prev) -> ((n - 1) * prev + x / :math.pow(prev, (n-1))) / n end
fixed_point(f, x, precision, f.(x))
end
defp fixed_point(_, guess, tolerance, next) when abs(guess - next) < tolerance, do: next
defp fixed_point(f, _, tolerance, next), do: fixed_point(f, next, tolerance, f.(next))
end
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)

View file

@ -0,0 +1 @@
=A1^(1/B1)

View file

@ -0,0 +1,39 @@
#NoTeS: This sample code does not validate inputs
# Thus, if there are errors the 'scary' red-text
# error messages will appear.
#
# This code will not work properly in floating point values of n,
# and negative values of A.
#
# Supports negative values of n by reciprocating the root.
$epsilon=1E-10 #Sample Epsilon (Precision)
function power($x,$e){ #As I said in the comment
$ret=1
for($i=1;$i -le $e;$i++){
$ret*=$x
}
return $ret
}
function root($y,$n){ #The main Function
if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} #This checks if n is negative.
$ans=1
do{
$d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp
$ans+=$d
} while ($d -lt -$epsilon -or $d -gt $epsilon)
if (0+$n -lt 0){return 1/$ans} else {return $ans}
}
#Sample Inputs
root 625 2
root 2401 4
root 2 -2
root 1.23456789E-20 34
root 9.87654321E20 10 #Quite slow here, I admit...
((root 5 2)+1)/2 #Extra: Computes the golden ratio
((root 5 2)-1)/2