Skip to content

Instantly share code, notes, and snippets.

@evadne
Last active June 25, 2017 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evadne/d32dc5eb544ecca95e97bdf4f0cd9ba3 to your computer and use it in GitHub Desktop.
Save evadne/d32dc5eb544ecca95e97bdf4f0cd9ba3 to your computer and use it in GitHub Desktop.
Cosine Similarity with Elixir
defmodule Script do
def cosine_similarity(lhs, rhs) do
{ab, aa, bb} = accumulate(lhs, rhs)
ab / (:math.sqrt(aa) * :math.sqrt(bb))
end
defp accumulate(lhs, rhs) do
accumulate(lhs, rhs, 0, 0, 0)
end
defp accumulate([], [], ab, aa, bb) do
{ab, aa, bb}
end
defp accumulate([h1|t1], [h2|t2], ab, aa, bb) do
accumulate(t1, t2,
ab + h1 * h2,
aa + h1 * h1,
bb + h2 * h2)
end
end
elixir_times = for (_ <- 1 .. 15) do
lhs = for (_ <- 1 .. 300), do: :rand.uniform()
rhs = for (_ <- 1 .. 300), do: :rand.uniform()
{result, _} = :timer.tc fn ->
Script.cosine_similarity(lhs, rhs)
end
result
end
elixir_average_time = elixir_times
|> (fn x -> Enum.sum(x) / length(x) end).()
IO.puts "elixir #{elixir_average_time}µs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment