How can I calculate a number with an exponent in Elixir?
For example, 23 would return 8.
:math.pow(2,3) #=> 8.0
If you want an integer:
:math.pow(2,3) |> round #=> 8
Erlang's :math.pow
has some limitations, for example it will not allow really high integer exponents:
iex(10)> :math.pow(2, 10000)
** (ArithmeticError) bad argument in arithmetic expression
You can easily reimplement a fast algorithm for computing exponentials that will work with the arbitrarily large integers provided by the runtime:
defmodule Pow do
require Integer
def pow(_, 0), do: 1
def pow(x, n) when Integer.is_odd(n), do: x * pow(x, n - 1)
def pow(x, n) do
result = pow(x, div(n, 2))
result * result
end
end
iex(9)> Pow.pow(2, 10000)
19950631168807583848837421626835850838234968318861924548520089498529438830...
Here is a tail call optimized implementation of the power function:
def pow(n, k), do: pow(n, k, 1)
defp pow(_, 0, acc), do: acc
defp pow(n, k, acc), do: pow(n, k - 1, n * acc)
:math.pow
's current implementation with an Erlang translation of this. github.com/erlang/otp
May 19, 2017 at 17:45
**/2
As of Elixir 1.13, **
is available.
> 2 ** 3
8
Note: it returns a float if the exponent is less than 0.
> elixir -v Elixir 1.13.0-rc.0 (5062a15) (compiled with Erlang/OTP 22)
and iex console: iex(1)> 2 ** 4
outputs 16
Nov 2, 2021 at 9:40
If the base is 2 and the power is an integer, you can do a left bitshift using the function Bitwise.bsl
. For example, 23 can be calculated with:
> Bitwise.bsl(1, 3)
8
Tis works - it will be great when I learn enough to know exactly why it works - probably something to do with eval under the covers:
defmodule Example do
require Integer
def do_it(list) do
list
|> Enum.reject(&Integer.is_odd(&1))
|> Enum.map(&(:math.pow(&1,3)))
end
end