Exponentiation operator

From Rosetta Code
Revision as of 11:01, 11 March 2010 by Toucan (talk | contribs) (→‎{{header|OCaml}}: generic pow)
Task
Exponentiation operator
You are encouraged to solve this task according to the task description, using any language you may know.

Most all programming languages have a built-in implementation of exponentiation. Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).

If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.

Ada

First we declare the specifications of the two procedures and the two corresponding operators (written as functions with quoted operators as their names): <lang ada>package Integer_Exponentiation is

  --  int^int
  procedure Exponentiate (Argument : in     Integer;
                          Exponent : in     Natural;
                          Result   :    out Integer);
  function "**" (Left  : Integer;
                 Right : Natural) return Integer;
  --  real^int
  procedure Exponentiate (Argument : in     Float;
                          Exponent : in     Integer;
                          Result   :    out Float);
  function "**" (Left  : Float;
                 Right : Integer) return Float;

end Integer_Exponentiation;</lang>

Now we can create a test program:

<lang ada>with Ada.Float_Text_IO, Ada.Integer_Text_IO, Ada.Text_IO; with Integer_Exponentiation;

procedure Test_Integer_Exponentiation is

  use Ada.Float_Text_IO, Ada.Integer_Text_IO, Ada.Text_IO;
  use Integer_Exponentiation;
  R : Float;
  I : Integer;

begin

  Exponentiate (Argument => 2.5, Exponent => 3, Result => R);
  Put ("2.5 ^ 3 = ");
  Put (R, Fore => 2, Aft => 4, Exp => 0);
  New_Line;
  Exponentiate (Argument => -12, Exponent => 3, Result => I);
  Put ("-12 ^ 3 = ");
  Put (I, Width => 7);
  New_Line;

end Test_Integer_Exponentiation;</lang>

Finally we can implement the procedures and operations:

<lang ada>package body Integer_Exponentiation is

  --  int^int
  procedure Exponentiate (Argument : in     Integer;
                          Exponent : in     Natural;
                          Result   :    out Integer) is
  begin
     Result := 1;
     for Counter in 1 .. Exponent loop
        Result := Result * Argument;
     end loop;
  end Exponentiate;
  function "**" (Left  : Integer;
                 Right : Natural) return Integer is
     Result : Integer;
  begin
     Exponentiate (Argument => Left,
                   Exponent => Right,
                   Result   => Result);
     return Result;
  end "**";
  --  real^int
  procedure Exponentiate (Argument : in     Float;
                          Exponent : in     Integer;
                          Result   :    out Float) is
  begin
     Result := 1.0;
     if Exponent < 0 then
        for Counter in Exponent .. -1 loop
           Result := Result / Argument;
        end loop;
     else
        for Counter in 1 .. Exponent loop
           Result := Result * Argument;
        end loop;
     end if;
  end Exponentiate;
  function "**" (Left  : Float;
                 Right : Integer) return Float is
     Result : Float;
  begin
      Exponentiate (Argument => Left,
                   Exponent => Right,
                   Result   => Result);
     return Result;
  end "**";

end Integer_Exponentiation;</lang>

ALGOL 68

<lang algol68>main:(

 INT two=2, thirty=30; # test constants #
 PROC VOID undefined;
  1. First implement exponentiation using a rather slow but sure FOR loop #
 PROC int pow = (INT base, exponent)INT: ( # PROC cannot be over loaded #
   IF exponent<0 THEN undefined FI;
   INT out:=( exponent=0 | 1 | base );
   FROM 2 TO exponent DO out*:=base OD;
   out
 );
 printf(($" One Gibi-unit is: int pow("g(0)","g(0)")="g(0)" - (cost: "g(0)
          " INT multiplications)"l$,two, thirty, int pow(two,thirty),thirty-1));
  1. implement exponentiation using a faster binary technique and WHILE LOOP #
 OP ** = (INT base, exponent)INT: (
   BITS binary exponent:=BIN exponent ; # do exponent arithmetic in binary #
   INT out := IF bits width ELEM binary exponent THEN base ELSE 1 FI;
   INT sq := IF exponent < 0 THEN undefined; ~ ELSE base FI;
   WHILE
     binary exponent := binary exponent SHR 1;
     binary exponent /= BIN 0
   DO
     sq *:= sq;
     IF bits width ELEM binary exponent THEN out *:= sq FI
   OD;
   out
 );
 printf(($" One Gibi-unit is: "g(0)"**"g(0)"="g(0)" - (cost: "g(0)
          " INT multiplications)"l$,two, thirty, two ** thirty,8));
 OP ** = (REAL in base, INT in exponent)REAL: ( # ** INT Operator can be overloaded #
   REAL base := ( in exponent<0 | 1/in base | in base);
   INT exponent := ABS in exponent;
   BITS binary exponent:=BIN exponent ; # do exponent arithmetic in binary #
   REAL out := IF bits width ELEM binary exponent THEN base ELSE 1 FI;
   REAL sq := base;
   WHILE
     binary exponent := binary exponent SHR 1;
     binary exponent /= BIN 0
   DO
     sq *:= sq;
     IF bits width ELEM binary exponent THEN out *:= sq FI
   OD;
   out
 );
 printf(($" One Gibi-unit is: "g(0,1)"**"g(0)"="g(0,1)" - (cost: "g(0)
          " REAL multiplications)"l$, 2.0, thirty, 2.0 ** thirty,8));
 OP ** = (REAL base, REAL exponent)REAL: ( # ** REAL Operator can be overloaded #
   exp(ln(base)*exponent)
 );
 printf(($" One Gibi-unit is: "g(0,1)"**"g(0,1)"="g(0,1)" - (cost: "
          "depends on precision)"l$, 2.0, 30.0, 2.0 ** 30.0))

)</lang> Output

One Gibi-unit is: int pow(2,30)=1073741824 - (cost: 29 INT multiplications)
One Gibi-unit is: 2**30=1073741824 - (cost: 8 INT multiplications)
One Gibi-unit is: 2.0**30=1073741824.0 - (cost: 8 REAL multiplications)
One Gibi-unit is: 2.0**30.0=1073741824.0 - (cost: depends on precision)

AutoHotkey

<lang AutoHotkey>MsgBox % Pow(5,3) MsgBox % Pow(2.5,4)

Pow(x, n){ r:=1 loop %n% r *= x return r }</lang>

AWK

This one-liner reads base and exponent from stdin, one pair per line, and writes the result to stdout: <lang awk>$ awk 'func pow(x,n){r=1;for(i=0;i<n;i++)r=r*x;return r}{print pow($1,$2)}' 2.5 2 6.25 10 6 1000000 3 0 1</lang>

C

Two versions are given - one for integer bases, the other for floating point. The integer version returns 0 when the abs(base) is != 1 and the exponent is negative. <lang c>#include <stdio.h> int ipow(int base, int exp) {

  int pow = base;
  int v = 1;
  if (exp < 0) {
     assert (base != 0);  /* divide by zero */
     return (base*base != 1)? 0: (exp&1)? base : 1;
  }
      
  while(exp > 0 )
  {
     if (exp & 1) v *= pow;
     pow *= pow;
     exp >>= 1;
   }
  return v;

}

double dpow(double base, int exp) {

  double v=1.0;
  double pow = (exp <0)? 1.0/base : base;
  if (exp < 0) exp = - exp;
  while(exp > 0 )
  {
     if (exp & 1) v *= pow;
     pow *= pow;
     exp >>= 1;
  }
  return v;

}

int main() {

   printf("2^6 = %d\n", (int)ipow(2,6));
   printf("2^-6 = %lf\n", ipow(2,-6));
   printf("2.71^6 = %lf\n", dpow(2.71,6));
   printf("2.71^-6 = %lf\n", dpow(2.71,-6));

}</lang>

C++

While C++ does allow operator overloading, it does not have an exponentiation operator, therefore only a function definition is given. For non-negative exponents the integer and floating point versions are exactly the same, for obvious reasons. For negative exponents, the integer exponentiation would not give integer results; therefore there are several possibilities:

  1. Use floating point results even for integer exponents.
  2. Use integer results for integer exponents and give an error for negative exponents.
  3. Use integer results for integer exponents and return just the integer part (i.e. return 0 if the base is larger than one and the exponent is negative).

The third option somewhat resembles the integer division rules, and has the nice property that it can use the exact same algorithm as the floating point version. Therefore this option is chosen here. Actually the template can be used with any type which supports multiplication, division and explicit initialization from int. Note that there are several aspects about int which are not portably defined; most notably it is not guaranteed

  • that the negative of a valid int is again a valid int; indeed for most implementations, the minimal value doesn't have a positive counterpart,
  • whether the result of a%b is positive or negative if a is negative, and in which direction the corresponding division is rounded (however, it is guaranteed that (a/b)*b + a%b == a)

The code below tries to avoid those platform dependencies. Note that bitwise operations wouldn't help here either, because the representation of negative numbers can vary as well. <lang cpp>template<typename Number>

Number power(Number base, int exponent)

{

 int zerodir;
 Number factor;
 if (exponent < 0)
 {
   zerodir = 1;
   factor = Number(1)/base;
 }
 else
 {
   zerodir = -1;
   factor = base;
 }
 Number result(1);
 while (exponent != 0)
 {
   if (exponent % 2 != 0)
   {
     result *= factor;
     exponent += zerodir;
   }
   else
   {
     factor *= factor;
     exponent /= 2;
   }
 }
 return result;

}</lang>

Chef

See Basic integer arithmetic#Chef.

Clojure

Operators in Clojure are functions, so this satisfies both requirements. Also, this is polymorphic- it will work with integers, floats, etc, even ratios. (Since operators are implemented as functions they are used in prefix notation) <lang lisp>(defn ** [x n] (reduce * (repeat n x)))</lang> Usage:

(** 2 3)        ; 8
(** 7.2 2.1)    ; 373.24800000000005
(** 7/2 3)      ; 343/8

Common Lisp

Common Lisp has a few forms of iteration. One of the more general is the do loop. Using the do loop, one definition is given below: <lang lisp>(defun my-expt-do (a b)

 (do ((x 1 (* x a))
      (y 0 (+ y 1)))
     ((= y b) x)))</lang>

do takes three forms. The first is a list of variable iniitializers and incrementers. In this case, x, the eventual return value, is initialized to 1, and every iteration of the do loop replaces the value of x with x * a. Similarly, y is initialized to 0 and is replaced with y + 1. The second is a list of conditions and return values. In this case, when y = b, the loop stops, and the current value of x is returned. Common Lisp has no explicit return keyword, so x ends up being the return value for the function. The last form is the body of the loop, and usually consists of some action to perform (that has some side-effect). In this case, all the work is being done by the first and second forms, so there are no extra actions.

Of course, Lisp programmers often prefer recursive solutions. <lang lisp>(defun my-expt-rec (a b)

 (cond 
   ((= b 0) 1)
   (t (* a (my-expt-rec a (- b 1))))))</lang>

This solution uses the fact that a^0 = 1 and that a^b = a * a^{b-1}. cond is essentially a generalized if-statement. It takes a list of forms of the form (cond result). For instance, in this case, if b = 0, then function returns 1. t is the truth constant in Common Lisp and is often used as a default condition (similar to the default keyword in C/C++/Java or the else block in many languages).

Common lisp has much more lenient rules for identifiers. In particular, ^ is a valid CL identifier. Since it is not already defined in the standard library, we can simply use it as a function name, just like any other function. <lang lisp>(defun ^ (a b)

 (do ((x 1 (* x a))
      (y 0 (+ y 1)))
     ((= y b) x)))</lang>

E

Simple, unoptimized implementation which will accept any kind of number for the base. If the base is an int, then the result will be of type float64 if the exponent is negative, and int otherwise.

<lang e>def power(base, exponent :int) {

   var r := base
   if (exponent < 0) {
       for _ in exponent..0 { r /= base }
   } else if (exponent <=> 0) {
       return 1
   } else {
       for _ in 2..exponent { r *= base }
   }
   return r

}</lang>

Factor

Simple, unoptimized implementation which accepts a positive or negative exponent: <lang factor>: pow ( f n -- f' )

   dup 0 < [ abs pow recip ]
   [ [ 1 ] 2dip swap [ * ] curry times ] if ;</lang> 

Here is a recursive implementation which splits the exponent in two: <lang factor>: pow ( f n -- f' )

   {  
       { [ dup 0 < ] [ abs pow recip ] }
       { [ dup 0 = ] [ 2drop 1 ] }
       [ [ 2 mod 1 = swap 1 ? ] [ [ sq ] [ 2 /i ] bi* pow ] 2bi * ]
   } cond ;</lang>

This implementation recurses only when an odd factor is found: <lang factor>USING: combinators kernel math ; IN: test

(pow) ( f n -- f' )
   [ dup even? ] [ [ sq ] [ 2 /i ] bi* ] while
   dup 1 = [ drop ] [ dupd 1 - (pow) * ] if ;
pow ( f n -- f' )
   {
       { [ dup 0 < ] [ abs (pow) recip ] }
       { [ dup 0 = ] [ 2drop 1 ] }
       [ (pow) ]
   } cond ;</lang>

A non-recursive version of (pow) can be written as: <lang factor>: (pow) ( f n -- f' )

   [ 1 ] 2dip     
   [ dup 1 = ] [
       dup even? [ [ sq ] [ 2 /i ] bi* ] [ [ [ * ] keep ] dip 1 - ] if
   ] until
   drop * ;</lang>

Forth

<lang forth>: ** ( n m -- n^m )

 1 swap  0 ?do over * loop  nip ;</lang>

<lang forth>: f**n ( f n -- f^n )

 dup 0= if
   drop fdrop 1e
 else dup 1 and if
   1- fdup recurse f*
 else
   2/ fdup f* recurse
 then then ;</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>MODULE Exp_Mod IMPLICIT NONE

INTERFACE OPERATOR (.pow.)  ! Using ** instead would overload the standard exponentiation operator

 MODULE PROCEDURE Intexp, Realexp

END INTERFACE

CONTAINS

 FUNCTION Intexp (base, exponent)
   INTEGER :: Intexp
   INTEGER, INTENT(IN) :: base, exponent
   INTEGER :: i
   IF (exponent < 0) THEN
      IF (base == 1) THEN
         Intexp = 1
      ELSE
         Intexp = 0
      END IF
      RETURN
   END IF
   Intexp = 1
   DO i = 1, exponent
     Intexp = Intexp * base
   END DO
 END FUNCTION IntExp
 FUNCTION Realexp (base, exponent)
   REAL :: Realexp
   REAL, INTENT(IN) :: base
   INTEGER, INTENT(IN) :: exponent
   INTEGER :: i
 
   Realexp = 1.0
   IF (exponent < 0) THEN
      DO i = exponent, -1
         Realexp = Realexp / base
      END DO
   ELSE  
      DO i = 1, exponent
         Realexp = Realexp * base
      END DO
   END IF
 END FUNCTION RealExp

END MODULE Exp_Mod

PROGRAM EXAMPLE USE Exp_Mod

 WRITE(*,*) 2.pow.30, 2.0.pow.30

END PROGRAM EXAMPLE</lang> Output

 1073741824    1.073742E+09

Haskell

Here's the exponentiation operator from the Prelude: <lang haskell>(^) :: (Num a, Integral b) => a -> b -> a _ ^ 0 = 1 x ^ n | n > 0 = f x (n-1) x where

 f _ 0 y = y
 f a d y = g a d  where
   g b i | even i  = g (b*b) (i `quot` 2)
         | otherwise = f b (i-1) (b*y)

_ ^ _ = error "Prelude.^: negative exponent"</lang>

There's no difference in Haskell between a procedure (or function) and an operator, other than the infix notation. This routine is overloaded for any integral exponent (which includes the arbitrarily large Integer type) and any numeric type for the bases (including, for example, Complex). It uses the fast "binary" exponentiation algorithm. For a negative exponent, the type of the base must support division (and hence reciprocals):

<lang haskell>(^^) :: (Fractional a, Integral b) => a -> b -> a x ^^ n = if n >= 0 then x^n else recip (x^(negate n))</lang>

This rules out e.g. the integer types as base values in this case. Haskell also has a third exponentiation operator,

<lang haskell>(**) :: Floating a => a -> a -> a x ** y = exp (log x * y)</lang> which is used for floating point arithmetic.

J

J is concretely specified, which makes it easy to define primitives in terms of other primitives (this is especially true of mathematical primitives, given the language's mathematical emphasis).

So we have any number of options. Here's the simplest, equivalent to the for each number, product = product * number of other languages. The base may be any number, and the exponent may be any non-negative integer (including zero):

<lang j> exp =. */@:#~

  10 exp 3

1000

  10 exp 0

1</lang>

We can make this more general by allowing the exponent to be any integer (including negatives), at the cost of a slight increase in complexity:

<lang j> exp =. *@:] %: */@:(#~|)

  10 exp _3

0.001</lang>

J also provides for a calculus of functions, permitting us to define exponentiation in its full generality, as the inverse of log (i.e. exp = log-1):

<lang j> exp =. ^.^:_1

81 exp 0.5   

9</lang>

Note that the definition above does not use the primitive exponentiation function ^ . The carets in it represent different (but related) things . The function is composed of three parts: ^. ^: _1 . The first part, ^., is the primitive logarithm operator (e.g. 3 = 10^.1000) .

The second part, ^: , is interesting: it is a "meta operator". It takes two arguments: a function f on its left, and a number N on its right. It produces a new function, which, when given an argument, applies f to that argument N times. For example, if we had a function increment, then increment^:3 X would increment X three times, so the result would be X+3.

In the case of ^. ^: _1 , f is ^. (i.e. logarithm) and N is -1. Therefore we apply log negative one times or the inverse of log once (precisely as in log-1).

Similarly, we can define log as the reverse of the inverse of root. That is, x pow y = y root-1 x:

<lang j> exp =.  %:^:_1~

81 exp 0.5

9</lang>

Compare this with the previous definition: it is the same, except that %: , root, has been substituted for ^. , logarithm, and the arguments have been reversed (or reflected) with ~.

That is, J is telling us that power is the same as the reflex of the inverse of root, exactly as we'd expect.

One last note: we said these definitions are the same as ^ in its full generality. What is meant by that? Well, in the context of this puzzle, it means both the base and exponent may be any real number. But J goes further than that: it also permits complex numbers.

Let's use Euler's famous formula, epi*i = -1 as an example:

<lang j> pi =. 3.14159265358979323846

  e  =. 2.71828182845904523536
  i  =. 2 %: _1                  NB.  Square root of -1
  
  e^(pi*i)

_1</lang>

And, as stated, our redefinition is equivalent:

<lang j> exp =. %:^:_1~

  e exp (pi*i)

_1</lang>

Java

Java does not support operator definition. This example is unoptimized, but will handle negative exponents as well. It is unnecessary to show intint since an int in Java will be cast as a double. <lang java>public class Exp{

  public static void main(String[] args){
     System.out.println(pow(2,30));
     System.out.println(pow(2.0,30)); //tests
     System.out.println(pow(2.0,-2));
  }
  public static double pow(double base, int exp){
     if(exp < 0) return 1 / pow(base, -exp);
     double ans = 1.0;
     for(;exp > 0;--exp) ans *= base;
     return ans;
  }

}</lang> Output:

1.073741824E9
1.073741824E9
0.25

JavaScript

<lang javascript>function pow(base, exp) {

   if (exp != Math.floor(exp)) 
       throw "exponent must be an integer";
   if (exp < 0) 
       return 1 / pow(base, -exp);
   var ans = 1;
   while (exp > 0) {
       ans *= base;
       exp--;
   }
   return ans;

}</lang>

<lang logo>to int_power :n :m

 if equal? 0 :m [output 1]
 if equal? 0 modulo :m 2 [output int_power :n*:n :m/2]
 output :n * int_power :n :m-1

end</lang>

Lucid

Some misconceptions about Lucid

<lang lucid>pow(n,x)

  k = n fby k div 2;
  p = x fby p*p;
  y =1 fby if even(k) then y else y*p;
  result y asa k eq 0;

end</lang>

M4

M4 lacks floating point computation and operator definition. <lang M4>define(`power',`ifelse($2,0,1,`eval($1*$0($1,decr($2)))')') power(2,10)</lang> Output:

1024

Mathematica

Define a function and an infix operator \[CirclePlus] with the same definition: <lang Mathematica>exponentiation[x_,y_Integer]:=Which[y>0,Times@@ConstantArray[x,y],y==0,1,y<0,1/exponentiation[x,-y]] CirclePlus[x_,y_Integer]:=exponentiation[x,y]</lang> Examples: <lang Mathematica>exponentiation[1.23,3] exponentiation[4,0] exponentiation[2.5,-2] 1.23\[CirclePlus]3 4\[CirclePlus]0 2.5\[CirclePlus]-2</lang> gives back: <lang Mathematica>1.86087 1 0.16 1.86087 1 0.16</lang> Note that \[CirclePlus] shows up as a special character in Mathematica namely a circle divided in 4 pieces. Note also that this function supports negative and positive exponents.

Modula-3

<lang modula3>MODULE Expt EXPORTS Main;

IMPORT IO, Fmt;

PROCEDURE IntExpt(arg, exp: INTEGER): INTEGER =

 VAR result := 1;
 BEGIN
   FOR i := 1 TO exp DO
     result := result * arg;
   END;
   RETURN result;
 END IntExpt;

PROCEDURE RealExpt(arg: REAL; exp: INTEGER): REAL =

 VAR result := 1.0;
 BEGIN
   IF exp < 0 THEN
     FOR i := exp TO -1 DO
       result := result / arg;
     END;
   ELSE
     FOR i := 1 TO exp DO
       result := result * arg;
     END;
   END;
   RETURN result;
 END RealExpt;

BEGIN

 IO.Put("2 ^ 4 = " & Fmt.Int(IntExpt(2, 4)) & "\n");
 IO.Put("2.5 ^ 4 = " & Fmt.Real(RealExpt(2.5, 4)) & "\n");

END Expt.</lang> Output:

2 ^ 4 = 16
2.5 ^ 4 = 39.0625

OCaml

The following operators only take nonnegative integer exponents. <lang ocaml>let expt_int a b =

 let rec aux x i =
   if i = b then x
   else aux (x * a) (i + 1)
 in
 aux 1 0

let expt_float a b =

 let rec aux x i =
   if i = b then x
   else aux (x *. a) (i + 1)
 in
 aux 1. 0

let ( ** ) = expt_int ;; (* hides the default infix operator *) let ( **. ) = expt_float ;;</lang>

<lang ocaml># 2 ** 3 ;; - : int = 8

  1. 2.4 **. 3 ;;

- : float = 13.824</lang>

It is possible to create a generic exponential. For this, one must know the multiplication function, and the unit value. Here, the usual fast algorithm is used.

<lang ocaml>let pow one mul a n = let rec g p x = function 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n;;


pow 1 ( * ) 2 16;; (* 65536 *) pow 1.0 ( *. ) 2.0 16;; (* 65536. *)

(* pow is not limited to exponentiation *) pow 0 ( + ) 2 16;; (* 32 *) pow "" ( ^ ) "abc " 10;; (* "abc abc abc abc abc abc abc abc abc abc " *) </lang>

Perl

<lang Perl>#!/usr/bin/perl -w use strict ;

sub expon {

  my ( $base , $expo ) = @_ ;
  if ( $expo == 0 ) {
     return 1 ;
  }
  elsif ( $expo == 1 ) {
     return $base ;
  }
  elsif ( $expo > 1 ) {
     my $prod = 1 ;
     foreach my $n ( 0..($expo - 1) ) {

$prod *= $base ;

     }
     return $prod ;
  }
  elsif ( $expo < 0 ) {
     return 1 / ( expon ( $base , -$expo ) ) ;
  }

} print "3 to the power of 10 as a function is " . expon( 3 , 10 ) . " !\n" ; print "3 to the power of 10 as a builtin is " . 3**10 . " !\n" ; print "5.5 to the power of -3 as a function is " . expon( 5.5 , -3 ) . " !\n" ; print "5.5 to the power of -3 as a builtin is " . 5.5**-3 . " !\n" ; </lang> Output:

3 to the power of 10 as a function is 59049 !
3 to the power of 10 as a builtin is 59049 !
5.5 to the power of -3 as a function is 0.00601051840721262 !
5.5 to the power of -3 as a builtin is 0.00601051840721262 !

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

<lang perl6>subset Natural of Int where { $^n >= 0 }

multi pow (0, 0) { fail '0**0 is undefined' } multi pow ($base, Natural $exp) { [*] $base xx $exp } multi pow ($base, Int $exp) { 1 / pow $base, -$exp }

sub infix:<***> ($a, $b) { pow $a, $b }</lang>

Examples of use:

<lang perl6>say pow .75, -5; say .75 *** -5;</lang>

PL/I

<lang PL/I> declare exp generic

 (iexp when (fixed, fixed),
  fexp when (float, fixed) );

iexp: procedure (m, n) returns (fixed binary (31));

  declare (m, n) fixed binary (31) nonassignable;
  declare exp fixed binary (31) initial (m), i fixed binary;
  if m = 0 & n = 0 then signal error;
  if n = 0 then return (1);
  do i = 2 to n;
     exp = exp * m;
  end;
  return (exp);

end iexp; fexp: procedure (a, n) returns (float (15));

  declare (a float, n fixed binary (31)) nonassignable;
  declare exp float initial (a), i fixed binary;
  if a = 0 & n = 0 then signal error;
  if n = 0 then return (1);
  do i = 2 to n;
     exp = exp * a;
  end;
  return (exp);

end fexp;</lang>

PowerShell

<lang powershell>function pow($a, [int]$b) {

   if ($b -eq -1) { return 1/$a }
   if ($b -eq 0)  { return 1 }
   if ($b -eq 1)  { return $a }
   if ($b -lt 0) {
       $rec = $true # reciprocal needed
       $b = -$b
   }
   $result = $a
   2..$b | ForEach-Object {
       $result *= $a
   }
   if ($rec) {
       return 1/$result
   } else {
       return $result
   }

}</lang> The function works for both integers and floating-point values as first argument.

PowerShell does not support operator overloading directly (and there wouldn't be an exponentiation operator to overload).

Output:

PS> pow 2 15
32768
PS> pow 2.71 -4
0,018540559532257
PS> pow (-1.35) 3
−2,460375

The negative first argument needs to be put in parentheses because it would otherwise be passed as string. This can be circumvented by declaring the first argument to the function as double, but then the return type would be always double while currently pow 2 3 returns an int.

Python

<lang python>>>> import operator >>> class num(int):

   def __pow__(self, b):
       print "Empowered"
       return operator.__pow__(self+0, b)


>>> x = num(3) >>> x**2 Empowered 9 >>> class num(float):

   def __pow__(self, b):
       print "Empowered"
       return operator.__pow__(self+0, b)


>>> x = num(2.5) >>> x**2 Empowered 6.25 >>></lang>

R

<lang r># Method pow <- function(x, y) {

  x <- as.numeric(x)
  y <- as.integer(y)   
  prod(rep(x, y))

}

  1. Operator

"%pow%" <- function(x,y) pow(x,y)

pow(3, 4) # 81 2.5 %pow% 2 # 6.25</lang>

Ruby

Works with: Ruby version 1.8.7

As a method: <lang ruby>class Numeric

 def pow(m)
   raise ArgumentError, "exponent must be an integer: #{m}" unless m.is_a?(Integer)
   puts "pow!!"
   # below requires ruby 1.8.7 or greater
   Array.new(m, self).inject(1, :*)   
   # for earlier versions of ruby without the "enum.inject(initial, sym)" method:
   #   res = 1
   #   m.times {res *= self}
   #   res
 end

end

p 5.pow(3) p 5.5.pow(3) p 5.pow(3.1)</lang> outputs

pow!!
125
pow!!
166.375
ArgumentError: exponent must be an integer: 3.1

To overload the ** exponentiation operator, this might work, but doesn't: <lang ruby>class Numeric

 def **(m)
   pow(m)
 end

end</lang> It doesn't work because the ** method is defined independently for Numeric subclasses Fixnum, Bignum and Float. One must: <lang ruby>class Fixnum

 def **(m)
   print "Fixnum "
   pow(m)
 end

end class Bignum

 def **(m)
   print "Bignum "
   pow(m)
 end

end class Float

 def **(m)
   print "Float "
   pow(m)
 end

end

p i=2**64 p i ** 2 p 2.2 ** 3</lang> which outputs

Fixnum pow!!
18446744073709551616
Bignum pow!!
340282366920938463463374607431768211456
Float pow!!
10.648

Scala

Works with: Scala version 2.8

There's no distinction between an operator and a method in Scala. Alas, there is no way of adding methods to a class, but one can make it look like a method has been added, through a method commonly known as Pimp My Library.

Therefore, we show below how that can be accomplished. We define the operator ↑ (unicode's uparrow), which is written as \u2191 below, to make cut&paste easier.

To use it, one has to import the implicit from the appropriate object. ExponentI will work for any integral type (Int, BigInt, etc), ExponentF will work for any fractional type (Double, BigDecimal, etc). Importing both at the same time won't work. In this case, it might be better to define implicits for the actual types being used, such as was done in Exponents.

<lang scala>object Exponentiation {

 import scala.annotation.tailrec
 
 @tailrec def powI[N](n: N, exponent: Int)(implicit num: Integral[N]): N = {
   import num._
   exponent match {
     case 0 => one
     case _ if exponent % 2 == 0 => powI((n * n), (exponent / 2))
     case _ => powI(n, (exponent - 1)) * n
   }
 }
 
 @tailrec def powF[N](n: N, exponent: Int)(implicit num: Fractional[N]): N = {
   import num._
   exponent match {
     case 0 => one
     case _ if exponent < 0 => one / powF(n, exponent.abs)
     case _ if exponent % 2 == 0 => powF((n * n), (exponent / 2))
     case _ => powF(n, (exponent - 1)) * n
   }
 }
 
 class ExponentI[N : Integral](n: N) {
   def \u2191(exponent: Int): N = powI(n, exponent)
 }
 class ExponentF[N : Fractional](n: N) {
   def \u2191(exponent: Int): N = powF(n, exponent)
 }
 object ExponentI {
   implicit def toExponentI[N : Integral](n: N): ExponentI[N] = new ExponentI(n)
 }
 
 object ExponentF {
   implicit def toExponentF[N : Fractional](n: N): ExponentF[N] = new ExponentF(n)
 }
 
 object Exponents {
   implicit def toExponent(n: Int): ExponentI[Int] = new ExponentI(n)
   implicit def toExponent(n: Double): ExponentF[Double] = new ExponentF(n)
 }

}</lang>

Scheme

This definition of the exponentiation procedure ^ operates on bases of all numerical types that the multiplication procedure * operates on, i. e. integer, rational, real, and complex. The notion of an operator does not exist in Scheme. Application of a procedure to its arguments is always expressed with a prefix notation. <lang scheme>(define (^ base exponent)

 (define (*^ exponent acc)
   (if (= exponent 0)
       acc
       (*^ (- exponent 1) (* acc base))))
 (*^ exponent 1))

(display (^ 2 3)) (newline) (display (^ (/ 1 2) 3)) (newline) (display (^ 0.5 3)) (newline) (display (^ 2+i 3)) (newline)</lang> Output:

8
1/8
0.125
2+11i

Seed7

In Seed7 the ** operator is overloaded for both intint and floatint. The following re-implementation of both functions does not use another exponentiation function to do the computation. Instead the the exponentiation by squaring algorithm is used.

<lang seed7>const func integer: intPow (in var integer: base, in var integer: exponent) is func

 result
   var integer: result is 0;
 begin
   if exponent < 0 then
     raise(NUMERIC_ERROR);
   else
     if odd(exponent) then
       result := base;
     else
       result := 1;
     end if;
     exponent := exponent div 2;
     while exponent <> 0 do
       base *:= base;
       if odd(exponent) then
         result *:= base;
       end if;
       exponent := exponent div 2;
     end while;
   end if;
 end func;</lang>

Original source: [1]

<lang seed7>const func float: fltIPow (in var float: base, in var integer: exponent) is func

 result
   var float: result is 0.0;
 local
   var boolean: neg_exp is FALSE;
 begin
   if base = 0.0 then
     if exponent < 0 then
       result := Infinity;
     elsif exponent = 0 then
       result := 1.0;
     else
       result := 0.0;
     end if;
   else
     if exponent < 0 then
       exponent := -exponent;
       neg_exp := TRUE;
     end if;
     # In the twos complement representation the most
     # negative number is the only one where both the
     # number and its negation are negative. When the
     # exponent is proven to be to the most negative
     # number fltIPow returns 0.0 .
     if exponent >= 0 then
       if odd(exponent) then
         result := base;
       else
         result := 1.0;
       end if;
       exponent >>:= 1;
       while exponent <> 0 do
         base *:= base;
         if odd(exponent) then
           result *:= base;
         end if;
         exponent >>:= 1;
       end while;
       if neg_exp then
         result := 1.0 / result;
       end if;
     end if;
   end if;
 end func;</lang>

Original source: [2]

Since Seed7 supports operator and function overloading a new exponentiation operator like ^* can be defined for both intint and floatint:

<lang seed7>$ syntax expr: .(). ^* .() is <- 4;

const func integer: (in var integer: base) ^* (in var integer: exponent) is

 return intPow(base, exponent);

const func float: (in var float: base) ^* (in var integer: exponent) is

 return fltIPow(base, exponent);</lang>

Slate

This code is from the current slate implementation: <lang slate>x@(Number traits) raisedTo: y@(Integer traits) [

 y isZero ifTrue: [^ x unit].
 x isZero \/ [y = 1] ifTrue: [^ x].
 y isPositive
   ifTrue:
     "(x * x raisedTo: y // 2) * (x raisedTo: y \\ 2)"
     [| count result |
      count: 1.
      [(count: (count bitShift: 1)) < y] whileTrue.
      result: x unit.
      [count isPositive]

whileTrue: [result: result squared. (y bitAnd: count) isZero ifFalse: [result: result * x]. count: (count bitShift: -1)].

      result]
   ifFalse: [(x raisedTo: y negated) reciprocal]

].</lang>

For floating numbers:

<lang slate>x@(Float traits) raisedTo: y@(Float traits) "Implements floating-point exponentiation in terms of the natural logarithm and exponential primitives - this is generally faster than the naive method." [

 y isZero ifTrue: [^ x unit].
 x isZero \/ [y isUnit] ifTrue: [^ x].
 (x ln * y) exp

].</lang>

Smalltalk

Works with: GNU Smalltalk

Extending the class Number, we provide the operator for integers, floating points, rationals numbers (and any other derived class) <lang smalltalk>Number extend [

 ** anInt [
      | r |
      ( anInt isInteger )
           ifFalse:
             [ '** works fine only for integer powers'

displayOn: stderr . Character nl displayOn: stderr ].

      r := 1.
      1 to: anInt do: [ :i | r := ( r * self ) ].
      ^r
 ]

].

( 2.5 ** 3 ) displayNl. ( 2 ** 10 ) displayNl. ( 3/7 ** 3 ) displayNl.</lang>

Outputs

15.625
1024
27/343

Standard ML

The following operators only take nonnegative integer exponents. <lang sml>fun expt_int (a, b) = let

 fun aux (x, i) =
   if i = b then x
   else aux (x * a, i + 1)

in

 aux (1, 0)

end

fun expt_real (a, b) = let

 fun aux (x, i) =
   if i = b then x
   else aux (x * a, i + 1)

in

 aux (1.0, 0)

end

val op ** = expt_int infix 6 ** val op *** = expt_real infix 6 ***</lang>

<lang sml>- 2 ** 3; val it = 8 : int - 2.4 *** 3; val it = 13.824 : real</lang>

Tcl

Works with: Tcl version 8.5

Tcl already has both an exponentiation function (set x [expr {pow(2.4, 3.5)}]) and operator (set x [expr {2.4 ** 3.5}]). The operator cannot be overridden. The function may be overridden by a procedure in the tcl::mathfunc namespace, relative to the calling namespace.

This solution does not consider negative exponents. <lang tcl>package require Tcl 8.5 proc tcl::mathfunc::mypow {a b} {

   if { ! [string is int -strict $b]} {error "exponent must be an integer"}
   set res 1
   for {set i 1} {$i <= $b} {incr i} {set res [expr {$res * $a}]}
   return $res

} expr {mypow(3, 3)} ;# ==> 27 expr {mypow(3.5, 3)} ;# ==> 42.875 expr {mypow(3.5, 3.2)} ;# ==> exponent must be an integer</lang>