Roots of a function: Difference between revisions
Content deleted Content added
Added Julia version |
Added Elixir |
||
Line 657:
(root f epsilon (- 2 epsilon)) → 1.0000000002190812 ;; 1
</lang>
=={{header|Elixir}}==
{{trans|Ruby}}
<lang elixir>defmodule RC do
def find_roots(f, range, step \\ 0.001) do
first .. last = range
max = last + step / 2
Stream.iterate(first, &(&1 + step))
|> Stream.take_while(&(&1 < max))
|> Enum.reduce(sign(first), fn x,sn ->
value = f.(x)
cond do
abs(value) < step / 100 ->
IO.puts "Root found at #{x}"
0
sign(value) == -sn ->
IO.puts "Root found between #{x-step} and #{x}"
-sn
true -> sign(value)
end
end)
end
defp sign(x) when x>0, do: 1
defp sign(x) when x<0, do: -1
defp sign(0) , do: 0
end
f = fn x -> x*x*x - 3*x*x + 2*x end
RC.find_roots(f, -1..3)</lang>
{{out}}
<pre>
Root found at 8.81239525796218e-16
Root found at 1.0000000000000016
Root found at 1.9999999999998914
</pre>
=={{header|Erlang}}==
|