Can this code be refactored into something more elegant?
defmodule Piapprox do
def iter_pi(epsilon) do
leibniz_stream |>
Enum.reduce_while(0, fn {i, n}, acc ->
if abs(:math.pi - acc) >= epsilon do
{ :cont, acc + i }
else
{ :halt, [n, Float.round(acc, 10)] }
end
end)
end
defp leibniz_stream do
Stream.unfold(1, fn
n when rem(n,4) == 1 -> { 4/n, n+2 }
n -> {-4/n, n+2 }
end) |> Stream.with_index
end
end
defmodule PiapproxTest do
use ExUnit.Case
def testPiApprox(nb, epsilon, ans) do
IO.puts("Test #{nb}")
assert Piapprox.iter_pi(epsilon) == ans
end
test "iter_pi" do
testPiApprox 1, 0.1, [ 10, 3.0418396189]
testPiApprox 2, 0.01, [ 100, 3.1315929036]
testPiApprox 3, 0.001, [ 1000, 3.1405926538]
testPiApprox 4, 7.001e-4, [ 1429, 3.1422924436]
testPiApprox 5, 6.001e-5, [ 16664, 3.1415326440]
end
end