Nathan Long
Nathan Long

Reputation: 126072

How do I raise a number to a power in Elixir?

How can I calculate a number with an exponent in Elixir?

For example, 23 would return 8.

Upvotes: 82

Views: 26966

Answers (7)

Nathan
Nathan

Reputation: 282

**/2

As of Elixir 1.13, ** is available.

> 2 ** 3 
8

Note: it returns a float if the exponent is less than 0.

Documentation

Upvotes: 20

Paweł Obrok
Paweł Obrok

Reputation: 23184

Edit: given **/2 exists now (see accepted answer), you should use it (or Integer.pow/2 for 1.12) instead of implementing one yourself, unless you're on elixir < 1.12.

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...

Upvotes: 75

Nathan Long
Nathan Long

Reputation: 126072

Integer.pow/2

As of v1.12, Integer.pow/2 is the way to do this.

Upvotes: 9

legoscia
legoscia

Reputation: 41618

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

Upvotes: 6

seagraph
seagraph

Reputation: 7

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

Upvotes: -3

markusheilig
markusheilig

Reputation: 178

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)

Upvotes: 16

Nathan Long
Nathan Long

Reputation: 126072

Use the Erlang :math module

:math.pow(2,3) #=> 8.0

If you want an integer:

:math.pow(2,3) |> round #=> 8

Upvotes: 89

Related Questions