LoginSignup
6
1

2分法をElixirで実装してみた

Posted at

授業で教えている2分法をElixirで実装してみましたので,報告します.

解答例

fn f, {a, b}, e ->
  if f.(a) * f.(b) < 0 do
    Stream.unfold({a, b}, fn
      {a, b} ->
        c = (a + b) / 2.0

        if f.(a) * f.(c) < 0 do
          {{a, c}, {a, c}}
        else
          {{c, b}, {c, b}}
        end
    end)
    |> Stream.drop_while(fn {a, b} -> abs(a - b) / 2 > e end)
    |> Enum.take(1)
    |> hd()
    |> elem(0)
    |> then(&Tuple.append({:ok}, &1))
  else
    {:error, "Solution is not found."}
  end
end
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1