dbdiaz has asked for the wisdom of the Perl Monks concerning the following question:

how do you calculate something like 2^3 = 8 in perl? is there a builtin function that i am missing? thanks!
  • Comment on some number to the power of any other number

Replies are listed 'Best First'.
Re: some number to the power of any other number
by ikegami (Patriarch) on Oct 31, 2006 at 06:24 UTC
    2**3

    or

    exp(log(2)*3)

    ** and other operators are documented in perlop. exp, log and other core functions (aka "named operators") are documented in perlfunc.

    Update: Added the exp-log expression. It's not very useful in Perl, but I threw it in since it's useful in languages without an exponentiation operator or function. In fact, ** is probably implemented as the exp-log expression.

Re: some number to the power of any other number
by bobf (Monsignor) on Oct 31, 2006 at 06:50 UTC

    You've already been pointed to the ** operator described in perlop, but I wanted to mention one other thing that may be relevant. How big are the numbers that you will be generating?

    If the values you are using are small, ** will work fine. If your code may generate very large numbers, however, you might want to look at Math::BigInt. There is a performance penalty that could become significant, so if you find that speed is an issue then Math::BigInt::GMP might help.

Re: some number to the power of any other number
by McDarren (Abbot) on Oct 31, 2006 at 06:25 UTC
    perldoc perlop is your friend...
    Exponentiation Binary "**" is the exponentiation operator. It binds even more tightl +y than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is implemented using C’s pow(3 +) function, which actually works on doubles internally.)

    Example:

    perl -le 'print 2**3' 8

    Cheers,
    Darren :)

Re: some number to the power of any other number
by lin0 (Curate) on Oct 31, 2006 at 20:03 UTC

    Hi dbdiaz

    Even though you already got the answer to your question: the ** operator described in perlop, I wanted to give you some advice: you should check the perl.org Online Library. There, you will find several books with the full text available. For instance, in the book Impatient Perl, you have that the numeric functions are described starting in page 15 (by the way, the ** operator is described on page 16).

    I hope this helps

    Cheers,

    lin0
Re: some number to the power of any other number
by dbdiaz (Novice) on Nov 01, 2006 at 06:13 UTC
    Thanks guys! I appreciate the fact that you even pointed me to some very useful resources! Thanks again.