Exponentiation operator: Difference between revisions

Added MiniScript
(Undo revision 285660 by Xbello (talk))
(Added MiniScript)
 
(42 intermediate revisions by 22 users not shown)
Line 9:
 
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both &nbsp; <big>int<sup>int</sup></big> &nbsp; and &nbsp; <big>float<sup>int</sup></big> &nbsp; variants.
 
<br><br>
 
;Related tasks:
* &nbsp; [[Exponentiation order]]
* &nbsp; [[Arbitrary-precision_integers_(included)|arbitrary-precision integers (included)]]
* &nbsp; [[Exponentiation with infix operators in (or operating on) the base]]
<br><br>
 
=={{header|11l}}==
{{trans|JavaScript}}
 
<syntaxhighlight lang="11l">F my_pow(base, exp) -> Float
I exp < 0
R 1 / my_pow(base, -exp)
I exp == 0
R 1
V ans = base
L 0 .< exp - 1
ans *= base
R ans
 
print(‘2 ^ 3 = ’my_pow(2, 3))
print(‘1 ^ -10 = ’my_pow(1, -10))
print(‘-1 ^ -3 = ’my_pow(-1, -3))
print()
print(‘2.0 ^ -3 = ’my_pow(2.0, -3))
print(‘1.5 ^ 0 = ’my_pow(1.5, 0))
print(‘4.5 ^ 2 = ’my_pow(4.5, 2))</syntaxhighlight>
 
{{out}}
<pre>
2 ^ 3 = 8
1 ^ -10 = 1
-1 ^ -3 = -1
 
2.0 ^ -3 = 0.125
1.5 ^ 0 = 1
4.5 ^ 2 = 20.25
</pre>
 
=={{header|68000 Assembly}}==
68000 Assembly has no built-in exponentiation. The easiest form of this operator to implement is a 32-bit unsigned version.
<syntaxhighlight lang="68000devpac">ExponentUnsigned:
;input: D0.W = BASE
; D1.W = EXPONENT
; OUTPUTS TO D0
; NO OVERFLOW PROTECTION - USE AT YOUR OWN RISK!
;HIGH WORDS OF D0 AND D1 ARE CLEARED.
;clobbers D1
MOVE.L D2,-(SP)
;using DBRAs lets us simultaneously subtract and compare
DBRA D1,.test_if_one
MOVEQ.L #1,D0 ;executes only if D1 was 0 to start with
.test_if_one:
DBRA D1,.go
bra .done ;executes only if D1 was 1 to start with
.go:
;else, multiply D0 by its ORIGINAL self repeatedly.
MOVE.L D0,D2
.loop:
MULU D0,D2
DBRA D1,.loop
MOVE.L D2,D0
.done:
MOVE.L (SP)+,D2
RTS</syntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
INT FUNC PowerI(INT base,exp)
INT res,i
 
IF exp<0 THEN Break() FI
 
res=1
FOR i=1 TO exp
DO
res==*base
OD
RETURN (res)
 
PROC PowerR(REAL POINTER base INT exp
REAL POINTER res)
INT i
REAL tmp
 
IF exp<0 THEN Break() FI
 
IntToReal(1,res)
FOR i=1 TO exp
DO
RealMult(res,base,tmp)
RealAssign(tmp,res)
OD
RETURN
 
PROC TestI(INT base,exp)
INT res
 
res=PowerI(base,exp)
PrintF("%I^%I=%I%E",base,exp,res)
RETURN
 
PROC TestR(REAL POINTER base INT exp)
REAL res
 
PowerR(base,exp,res)
PrintR(base) PrintF("^%I=",exp)
PrintRE(res)
RETURN
 
PROC Main()
REAL base
 
Put(125) PutE() ;clear screen
 
TestI(27,3)
TestI(2,12)
TestI(-3,9)
TestI(1,1000)
TestI(20000,0)
ValR("3.141592654",base)
TestR(base,10)
ValR("-1.11",base)
TestR(base,99)
ValR("0.123456789",base)
TestR(base,1)
ValR("987654.321",base)
TestR(base,0)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Exponentiation_operator.png Screenshot from Atari 8-bit computer]
<pre>
27^3=19683
2^12=4096
-3^9=-19683
1^1000=1
20000^0=1
3.14159265^10=93648.046
-1.11^99=-30688.4433
.123456789^1=.123456789
987654.321^0=1
</pre>
 
=={{header|Ada}}==
 
First we declare the specifications of the two procedures and the two corresponding operators (written as functions with quoted operators as their names):
<langsyntaxhighlight lang="ada">package Integer_Exponentiation is
-- int^int
procedure Exponentiate (Argument : in Integer;
Line 28 ⟶ 176:
function "**" (Left : Float;
Right : Integer) return Float;
end Integer_Exponentiation;</langsyntaxhighlight>
 
Now we can create a test program:
 
<langsyntaxhighlight lang="ada">with Ada.Float_Text_IO, Ada.Integer_Text_IO, Ada.Text_IO;
with Integer_Exponentiation;
 
Line 50 ⟶ 198:
Put (I, Width => 7);
New_Line;
end Test_Integer_Exponentiation;</langsyntaxhighlight>
 
Finally we can implement the procedures and operations:
 
<langsyntaxhighlight lang="ada">package body Integer_Exponentiation is
-- int^int
procedure Exponentiate (Argument : in Integer;
Line 102 ⟶ 250:
return Result;
end "**";
end Integer_Exponentiation;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 109 ⟶ 257:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - formatted transput used in the test output}}
<langsyntaxhighlight lang="algol68">main:(
INT two=2, thirty=30; # test constants #
PROC VOID undefined;
Line 169 ⟶ 317:
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))
)</langsyntaxhighlight>
{{out}}
<pre>One Gibi-unit is: int pow(2,30)=1073741824 - (cost: 29 INT multiplications)
Line 181 ⟶ 329:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - formatted transput used in the test output}}
<langsyntaxhighlight lang="algol68">main:(
INT two=2, thirty=30; # test constants #
PROC VOID undefined;
Line 230 ⟶ 378:
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))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 238 ⟶ 386:
One Gibi-unit is: 2.0**30.0=1073741824.0 - (cost: depends on precision)
</pre>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">on exponentiationOperatorTask(n, power)
set power to power as integer
set operatorResult to (n ^ power)
set handlerResult to exponentiate(n, power)
return {operator:operatorResult, |handler|:handlerResult}
end exponentiationOperatorTask
 
on exponentiate(n, power)
-- AppleScript's ^ operator returns a real (ie. float) result. This handler does the same.
set n to n as real
set out to 1.0
if (power < 0) then
repeat -power times
set out to out / n
end repeat
else
repeat power times
set out to out * n
end repeat
end if
return out
end exponentiate
 
exponentiationOperatorTask(3, 3) --> {operator:27.0, |handler|:27.0}
exponentiationOperatorTask(2, 16) --> {operator:6.5536E+4, |handler|:6.5536E+4}
exponentiationOperatorTask(2.5, 10) --> {operator:9536.7431640625, |handler|:9536.7431640625}
exponentiationOperatorTask(2.5, -10) --> {operator:1.048576E-4, |handler|:1.048576E-4}</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">myPow: function [base,xp][
if xp < 0 [
(floating? base)? -> return 1 // myPow base neg xp
-> return 1 / myPow base neg xp
]
 
if xp = 0 ->
return 1
 
ans: 1
while [xp > 0][
ans: ans * base
xp: xp - 1
]
return ans
]
 
print ["2 ^ 3 =" myPow 2 3]
print ["1 ^ -10 =" myPow 1 neg 10]
print ["-1 ^ -3 =" myPow neg 1 neg 3]
print ""
print ["2.0 ^ -3 =" myPow 2.0 neg 3]
print ["1.5 ^ 0 =" myPow 1.5 0]
print ["4.5 ^ 2 =" myPow 4.5 2]</syntaxhighlight>
 
{{out}}
 
<pre>2 ^ 3 = 8
1 ^ -10 = 1
-1 ^ -3 = -1
 
2.0 ^ -3 = 0.125
1.5 ^ 0 = 1
4.5 ^ 2 = 20.25</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % Pow(5,3)
MsgBox % Pow(2.5,4)
 
Line 248 ⟶ 464:
r *= x
return r
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 254 ⟶ 470:
Traditional awk implementations do not provide an exponent operator, so we define a function to calculate the exponent.
This one-liner reads base and exponent from stdin, one pair per line, and writes the result to stdout:
<langsyntaxhighlight lang="awk">$ awk 'function pow(x,n){r=1;for(i=0;i<n;i++)r=r*x;return r}{print pow($1,$2)}'
</syntaxhighlight>
</lang>
 
{{out}}
Line 271 ⟶ 487:
</pre>
 
<langsyntaxhighlight lang="awk">If you want to use arbitrary precision number with (more recent) awk, you have to use -M option :
$ gawk -M '{ printf("%f\n",$1^$2) }'
</syntaxhighlight>
</lang>
 
{{out}}
Line 281 ⟶ 497:
</pre>
 
<langsyntaxhighlight lang="awk">And if you want to use locales for decimal separator, you have tu use -N option :
$ gawk -N '{ printf("%f\n",$1^$2) }'
</syntaxhighlight>
</lang>
 
{{out}}
Line 296 ⟶ 512:
The vast majority of BASIC implementations don't support defining custom operators, or overloading of any kind.
 
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION powL& (x AS INTEGER, y AS INTEGER)
DECLARE FUNCTION powS# (x AS SINGLE, y AS INTEGER)
 
Line 334 ⟶ 550:
END IF
powS# = m
END FUNCTION</langsyntaxhighlight>
 
{{out}}
Line 345 ⟶ 561:
9.712946 2 94.34131879665438
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">ni = int(rand * 10)
nf = round(rand * 10, 4)
ex = int(rand * 10)
print " "; ni; " ^ "; ex; " = "; iPow (ni, ex)
print nf; " ^ "; ex; " = "; fPow (nf, ex)
end
 
function iPow (base, exponent)
if exponent = 0 then return 1
if exponent = 1 then return base
if exponent < 0 then return 1 / iPow(base, -exponent)
power = base
for i = 2 to exponent
power *= base
next
return power
end function
 
function fPow (base, exponent)
if exponent = 0.0 then return 1.0
if exponent = 1.0 then return base
if exponent < 0.0 then return 1.0 / fPow(base, -exponent)
power = base
for i = 2 to exponent
power *= base
next
return power
end function</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">RANDOMIZE
 
FUNCTION fPow (base, exponent)
IF exponent = 0.0 THEN LET fPow = 1.0
IF exponent = 1.0 THEN LET fPow = base
IF exponent < 0.0 THEN LET fPow = 1.0 / fPow(base, -exponent)
LET power = base
FOR i = 2 TO exponent
LET power = power * base
NEXT i
LET fPow = power
END FUNCTION
 
FUNCTION iPow (base, exponent)
IF exponent = 0 THEN LET iPow = 1
IF exponent = 1 THEN LET iPow = base
IF exponent < 0 THEN LET iPow = 1 / iPow(base, -exponent)
LET power = base
FOR i = 2 TO exponent
LET power = power * base
NEXT i
LET iPow = power
END FUNCTION
 
LET ni = ROUND(INT(RND * 10))
LET nf = RND * 10
LET ex = INT(RND * 10)
PRINT ni; " ^ "; ex; " = "; iPow (ni, ex)
PRINT nf; " ^ "; ex; " = "; fPow (nf, ex)
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub iPow (base, exponent)
local power
if exponent = 0 return 1
if exponent = 1 return base
if exponent < 0 return 1 / iPow(base, -exponent)
power = base
for i = 2 to exponent
power = power * base
next
return power
end sub
 
sub fPow (base, exponent)
local power
if exponent = 0.0 return 1.0
if exponent = 1.0 return base
if exponent < 0.0 return 1.0 / fPow(base, -exponent)
power = base
for i = 2 to exponent
power = power * base
next
return power
end sub
 
ni = round(ran(10))
nf = ran(10)
ex = int(ran(10))
print ni, " ^ ", ex, " = ", iPow (ni, ex)
print nf, " ^ ", ex, " = ", fPow (nf, ex)
end</syntaxhighlight>
 
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> PRINT "11^5 = " ; FNipow(11, 5)
PRINT "PI^3 = " ; FNfpow(PI, 3)
END
Line 369 ⟶ 682:
B% = B% << 1
NEXT
= P</langsyntaxhighlight>
{{out}}
<pre>11^5 = 161051
Line 375 ⟶ 688:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 DEF POW(X,Y)
110 IF X=0 THEN LET POW=0:EXIT DEF
120 LET POW=EXP(Y*LOG(X))
130 END DEF
140 PRINT POW(PI,3)
150 PRINT PI^3</langsyntaxhighlight>
 
=={{header|Befunge}}==
Note: Only works for integer bases and powers.
<langsyntaxhighlight lang="befunge">v v \<
>&:32p&1-\>32g*\1-:|
$
.
@</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">#Procedure
exp = { base, exp |
1.to(exp).reduce 1, { m, n | m = m * base }
Line 403 ⟶ 716:
 
p exp 2 5 #Prints 32
p 2 ^ 5 #Prints 32</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <assert.h>
 
Line 450 ⟶ 763:
printf("2.71^6 = %lf\n", dpow(2.71,6));
printf("2.71^-6 = %lf\n", dpow(2.71,-6));
}</langsyntaxhighlight>
 
The C11 standard features type-generic expressions via the _Generic keyword. We can add to the above example to use this feature.
{{works with|Clang|3.0+}}
<syntaxhighlight lang="c">
<lang c>
#define generic_pow(base, exp)\
_Generic((base),\
Line 468 ⟶ 781:
printf("2.71^-6 = %lf\n", generic_pow(2.71,-6));
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Line 481 ⟶ 794:
--[[User:LordMike|LordMike]] 17:45, 5 May 2010 (UTC)
 
<langsyntaxhighlight lang="csharp">
static void Main(string[] args)
{
Line 497 ⟶ 810:
return Math.Pow(Val, Pow);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 514 ⟶ 827:
* whether the result of <tt>a%b</tt> is positive or negative if <tt>a</tt> is negative, and in which direction the corresponding division is rounded (however, it ''is'' guaranteed that <tt>(a/b)*b + a%b == a</tt>)
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.
<langsyntaxhighlight lang="cpp">template<typename Number>
Number power(Number base, int exponent)
{
Line 545 ⟶ 858:
}
return result;
}</langsyntaxhighlight>
 
=={{header|Chef}}==
Line 552 ⟶ 865:
=={{header|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)
<langsyntaxhighlight lang="lisp">(defn ** [x n] (reduce * (repeat n x)))</langsyntaxhighlight>
Usage:
<pre>(** 2 3) ; 8
Line 560 ⟶ 873:
=={{header|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:
<langsyntaxhighlight lang="lisp">(defun my-expt-do (a b)
(do ((x 1 (* x a))
(y 0 (+ y 1)))
((= y b) x)))</langsyntaxhighlight>
<tt>do</tt> takes three forms. The first is a list of variable initializers and incrementers. In this case, <tt>x</tt>, the eventual return value, is initialized to 1, and every iteration of the <tt>do</tt> loop replaces the value of <tt>x</tt> with ''x * a''. Similarly, <tt>y</tt> 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 <tt>x</tt> is returned. Common Lisp has no explicit return keyword, so <tt>x</tt> 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.
<langsyntaxhighlight lang="lisp">(defun my-expt-rec (a b)
(cond
((= b 0) 1)
(t (* a (my-expt-rec a (- b 1))))))</langsyntaxhighlight>
This solution uses the fact that a^0 = 1 and that a^b = a * a^{b-1}. <tt>cond</tt> 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 <tt>default</tt> keyword in C/C++/Java or the <tt>else</tt> block in many languages).
 
Common Lisp has much more lenient rules for identifiers. In particular, <tt>^</tt> 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.
<langsyntaxhighlight lang="lisp">(defun ^ (a b)
(do ((x 1 (* x a))
(y 0 (+ y 1)))
((= y b) x)))</langsyntaxhighlight>
 
=={{header|D}}==
Line 583 ⟶ 896:
 
D has a built-in exponentiation operator: ^^
<langsyntaxhighlight lang="d">import std.stdio, std.conv;
 
struct Number(T) {
Line 629 ⟶ 942:
writeln(Int(3) ^^ 3);
writeln(Int(0) ^^ -2); // Division by zero.
}</langsyntaxhighlight>
{{out}}
(Compiled in debug mode, stack trace removed)
Line 638 ⟶ 951:
27
opBinary</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
program Exponentiation_operator;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
type
TDouble = record
Value: Double;
class operator Implicit(a: TDouble): Double;
class operator Implicit(a: Double): TDouble;
class operator Implicit(a: TDouble): string;
class operator LogicalXor(a: TDouble; b: Integer): TDouble;
end;
 
TInteger = record
Value: Integer;
class operator Implicit(a: TInteger): Integer;
class operator Implicit(a: Integer): TInteger;
class operator Implicit(a: TInteger): string;
class operator LogicalXor(a: TInteger; b: Integer): TInteger;
end;
 
{ TDouble }
 
class operator TDouble.Implicit(a: TDouble): Double;
begin
Result := a.Value;
end;
 
class operator TDouble.Implicit(a: Double): TDouble;
begin
Result.Value := a;
end;
 
class operator TDouble.Implicit(a: TDouble): string;
begin
Result := a.Value.ToString;
end;
 
class operator TDouble.LogicalXor(a: TDouble; b: Integer): TDouble;
var
i: Integer;
val: Double;
begin
val := 1;
for i := 1 to b do
val := val * a.Value;
Result.Value := val;
end;
 
{ TInteger }
 
class operator TInteger.Implicit(a: TInteger): Integer;
begin
Result := a.Value;
end;
 
class operator TInteger.Implicit(a: Integer): TInteger;
begin
Result.Value := a;
end;
 
class operator TInteger.Implicit(a: TInteger): string;
begin
Result := a.Value.ToString;
end;
 
class operator TInteger.LogicalXor(a: TInteger; b: Integer): TInteger;
var
val, i: Integer;
begin
if b < 0 then
raise Exception.Create('Expoent must be greater or equal zero');
 
val := 1;
for i := 1 to b do
val := val * a.Value;
Result.Value := val;
end;
 
procedure Print(s: string);
begin
Write(s);
end;
 
var
valF: TDouble;
valI: TInteger;
 
begin
valF := 5.5;
valI := 5;
 
// Delphi don't have "**" or "^" operator for overload,
// "xor" operator has used instead
Print('5^5 = ');
Print(valI xor 5);
print(#10);
 
Print('5.5^5 = ');
Print(valF xor 5);
print(#10);
 
readln;
end.</syntaxhighlight>
{{out}}
<pre>5^5 = 3125
5.5^5 = 5032,84375</pre>
 
=={{header|E}}==
Simple, unoptimized implementation which will accept any kind of number for the base. If the base is an <code>int</code>, then the result will be of type <code>float64</code> if the exponent is negative, and <code>int</code> otherwise.
 
<langsyntaxhighlight lang="e">def power(base, exponent :int) {
var r := base
if (exponent < 0) {
Line 652 ⟶ 1,078:
}
return r
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
func mypow n exp .
r = 1
if exp < 0
exp = -exp
n = 1 / n
.
for i to exp
r *= n
.
return r
.
print mypow pi 2
print mypow 2 -2
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; this exponentiation function handles integer, rational or float x.
;; n is a positive or negative integer.
Line 682 ⟶ 1,125:
38540524895511613165266748863173814985473295063157418576769816295283207864908351682948692085553606681763707358759878656
 
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Line 688 ⟶ 1,131:
Ela standard prelude already defines an exponentiation operator (**) but we will implement it by ourselves anyway:
 
<langsyntaxhighlight lang="ela">open number
 
_ ^ 0 = 1
Line 698 ⟶ 1,141:
| else = f b (i - 1) (b * y)
 
(12 ^ 4, 12 ** 4)</langsyntaxhighlight>
 
{{out}}
Line 706 ⟶ 1,149:
and make it generic:
 
<langsyntaxhighlight lang="ela">open number
 
//Function quot from number module is defined only for
Line 725 ⟶ 1,168:
 
 
(12 ^ 4, 12.34 ^ 4.04)</langsyntaxhighlight>
 
{{out}}
Line 734 ⟶ 1,177:
work with overloading (less preferable in this case because of more redundant code but still possible):
 
<langsyntaxhighlight lang="ela">open number
 
//A class that defines our overloadable function
Line 761 ⟶ 1,204:
| else = f b (i - 1) (b * y)
 
(12 ^ 4, 12.34 ^ 4.04)</langsyntaxhighlight>
 
{{out}}
Line 767 ⟶ 1,210:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule My do
def exp(x,y) when is_integer(x) and is_integer(y) and y>=0 do
IO.write("int> ") # debug test
Line 797 ⟶ 1,240:
spow = inspect :math.pow(x,y) # For the comparison
:io.fwrite("~10s = ~12s, ~12s~n", [sxy, sexp, spow])
end)</langsyntaxhighlight>
 
{{out}}
Line 821 ⟶ 1,264:
 
pow(number, integer) -> number
<langsyntaxhighlight lang="erlang">
pow(X, Y) when Y < 0 ->
1/pow(X, -Y);
Line 832 ⟶ 1,275:
B2 = if Y rem 2 =:= 0 -> B; true -> X * B end,
pow(X * X, Y div 2, B2).
</syntaxhighlight>
</lang>
 
Tail call optimised version which works for both integers and float bases.
Line 840 ⟶ 1,283:
handles *integer powers*: for floating point exponent you must use EXP and LOG predefined
functions.
<langsyntaxhighlight ERRElang="erre">PROGRAM POWER
 
PROCEDURE POWER(A,B->POW) ! this routine handles only *INTEGER* powers
Line 855 ⟶ 1,298:
POWER(11,-2->POW) PRINT(POW)
POWER(π,3->POW) PRINT(POW)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre> 8.264463E-03
Line 862 ⟶ 1,305:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//Integer Exponentiation, more interesting anyway than repeated multiplication. Nigel Galloway, October 12th., 2018
let rec myExp n g=match g with
Line 870 ⟶ 1,313:
 
printfn "%d" (myExp 3 15)
</syntaxhighlight>
</lang>
{{out}}
<pre>
14348907
</pre>
 
=={{header|Factor}}==
Simple, unoptimized implementation which accepts a positive or negative exponent:
<langsyntaxhighlight lang="factor">: pow ( f n -- f' )
dup 0 < [ abs pow recip ]
[ [ 1 ] 2dip swap [ * ] curry times ] if ;</langsyntaxhighlight>
 
Here is a recursive implementation which splits the exponent in two:
<langsyntaxhighlight 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 ;</langsyntaxhighlight>
 
This implementation recurses only when an odd factor is found:
<langsyntaxhighlight lang="factor">USING: combinators kernel math ;
IN: test
 
Line 902 ⟶ 1,346:
{ [ dup 0 = ] [ 2drop 1 ] }
[ (pow) ]
} cond ;</langsyntaxhighlight>
 
A non-recursive version of (pow) can be written as:
<langsyntaxhighlight lang="factor">: (pow) ( f n -- f' )
[ 1 ] 2dip
[ dup 1 = ] [
dup even? [ [ sq ] [ 2 /i ] bi* ] [ [ [ * ] keep ] dip 1 - ] if
] until
drop * ;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: ** ( n m -- n^m )
1 swap 0 ?do over * loop nip ;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="forth">: f**n ( f n -- f^n )
dup 0= if
drop fdrop 1e
Line 923 ⟶ 1,367:
else
2/ fdup f* recurse
then then ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE Exp_Mod
IMPLICIT NONE
 
Line 977 ⟶ 1,421:
USE Exp_Mod
WRITE(*,*) 2.pow.30, 2.0.pow.30
END PROGRAM EXAMPLE</langsyntaxhighlight>
{{out}}
<pre>
Line 984 ⟶ 1,428:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0
 
' Note that 'base' is a keyword in FB, so we use 'base_' instead as a parameter
Line 1,015 ⟶ 1,459:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,029 ⟶ 1,473:
1.78 ^ 3 = 5.639752000000001
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn CustomPOW( base as double, exponent as NSInteger ) as double
double power = base, result
NSUInteger i
if exponent = 0.0 then result = 1.0 : exit fn
if exponent = 1.0 then result = base : exit fn
if exponent < 0.0
for i = 2 to -exponent
power = power * base
next
result = 1.0/power : exit fn
end if
for i = 2 to exponent
power = power * base
next
result = power
end fn = result
 
print "Custom POW function:"
print "fn CustomPOW( 2, 2 ) = "; fn CustomPOW( 2, 2 )
print "fn CustomPOW( 2.5, 2 ) = "; fn CustomPOW( 2.5, 2 )
print "fn CustomPOW( 2, -3 ) = "; fn CustomPOW( 2, -3 )
print "fn CustomPOW( 1.78, 3 ) = "; fn CustomPOW( 1.78, 3 )
print "fn CustomPOW( 5.5, 5 ) = "; fn CustomPOW( 5.5, 5 )
print "fn CustomPOW( 4.5, 2 ) = "; fn CustomPOW( 4.5, 2 )
print "fn CustomPOW( -1, -3 ) = "; fn CustomPOW( -1, -3 )
print
print "Native FB ^ operator:"
print "2^2 = "; 2^2
print "2.5^2 = "; 2.5^2
print "2^-3 = "; 2^-3
print "1.78^3 = "; 1.78^3
print "5.5^5 = "; 5.5^5
print "4.5^2 = "; 4.5^2
print "-1^=3 = "; -1^-3
print
print "Native FB fn POW function:"
print "fn POW( 2, 2 ) = "; fn POW( 2, 2 )
print "fn POW( 2.5, 2 ) = "; fn POW( 2.5, 2 )
print "fn POW( 2, -3 ) = "; fn POW( 2, -3 )
print "fn POW( 1.78, 3 ) = "; fn POW( 1.78, 3 )
print "fn POW( 5.5, 5 ) = "; fn POW( 5.5, 5 )
print "fn POW( 4.5, 2 ) = "; fn POW( 4.5, 2 )
print "fn POW( -1, -3 ) = "; fn POW( -1, -3 )
print
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Custom POW function:
fn CustomPOW( 2, 2 ) = 4
fn CustomPOW( 2.5, 2 ) = 6.25
fn CustomPOW( 2, -3 ) = 0.125
fn CustomPOW( 1.78, 3 ) = 5.639752000000001
fn CustomPOW( 5.5, 5 ) = 5032.84375
fn CustomPOW( 4.5, 2 ) = 20.25
fn CustomPOW( -1, -3 ) = -1
 
Native FB ^ operator:
2^2 = 4
2.5^2 = 6.25
2^-3 = 0.125
1.78^3 = 5.639752000000001
5.5^5 = 5032.84375
4.5^2 = 20.25
-1^=3 = -1
 
Native FB fn POW function:
fn POW( 2, 2 ) = 4
fn POW( 2.5, 2 ) = 6.25
fn POW( 2, -3 ) = 0.125
fn POW( 1.78, 3 ) = 5.639752000000001
fn POW( 5.5, 5 ) = 5032.84375
fn POW( 4.5, 2 ) = 20.25
fn POW( -1, -3 ) = -1
</pre>
 
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">expon := function(a, n, one, mul)
local p;
p := one;
Line 1,050 ⟶ 1,575:
List([0 .. 31], n -> (1 - expon(0, n, 1, \-))/2);
# [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
# 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 ]</langsyntaxhighlight>
 
=={{header|Go}}==
Go doesn't support operator defintion. Other notes: While I left the integer algorithm simple, I used the shift and square trick for the float algorithm, just to show an alternative.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,130 ⟶ 1,655:
tf(10, -39)
tf(-10, 39)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,158 ⟶ 1,683:
=={{header|Haskell}}==
Here's the exponentiation operator from the Prelude:
<langsyntaxhighlight lang="haskell">(^) :: (Num a, Integral b) => a -> b -> a
_ ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x where
Line 1,165 ⟶ 1,690:
g b i | even i = g (b*b) (i `quot` 2)
| otherwise = f b (i-1) (b*y)
_ ^ _ = error "Prelude.^: negative exponent"</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight lang="haskell">(^^) :: (Fractional a, Integral b) => a -> b -> a
x ^^ n = if n >= 0 then x^n else recip (x^(negate n))</langsyntaxhighlight>
 
This rules out e.g. the integer types as base values in this case. Haskell also has a third exponentiation operator,
 
<langsyntaxhighlight lang="haskell">(**) :: Floating a => a -> a -> a
x ** y = exp (log x * y)</langsyntaxhighlight>
which is used for floating point arithmetic.
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">WRITE(Clipboard) pow(5, 3) ! 125
WRITE(ClipBoard) pow(5.5, 7) ! 152243.5234
 
Line 1,187 ⟶ 1,712:
pow = pow * x
ENDDO
END </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The procedure below will take an integer or real base and integer exponent and return base ^ exponent. If exponent is negative, base is coerced to real so as not to return 0. Operator overloading is not supported and this is not an efficient implementation.
<langsyntaxhighlight Iconlang="icon">procedure main()
bases := [5,5.]
numbers := [0,2,2.,-1,3]
Line 1,212 ⟶ 1,737:
res := op(res,base)
return res
end</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,219 ⟶ 1,744:
So we have any number of options. Here's the simplest, equivalent to the <code>for each number, product = product * number</code> of other languages. The base may be any number, and the exponent may be any non-negative integer (including zero):
 
<langsyntaxhighlight lang="j"> exp =: */@:#~
10 exp 3
Line 1,225 ⟶ 1,750:
10 exp 0
1</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="j"> exp =: *@:] %: */@:(#~|)
10 exp _3
0.001</langsyntaxhighlight>
 
Or, we can define exponentiation as repeated multiplication (as opposed to multiplying a given number of copies of the base)
 
<langsyntaxhighlight Jlang="j"> exp =: dyad def 'x *^:y 1'
 
10 exp 3
1000
10 exp _3
0.001</langsyntaxhighlight>
 
Here, when we specify a negative number of repetitions, multiplication's inverse is used that many times.
Line 1,247 ⟶ 1,772:
J's calculus of functions permits us to define exponentiation in its full generality, as the '''inverse of log''' (i.e. ''exp = log<sup>-1</sup>''):
 
<langsyntaxhighlight lang="j"> exp =: ^.^:_1
81 exp 0.5
9</langsyntaxhighlight>
 
Note that the definition above does '''not''' use the primitive exponentiation function <code>^</code> . The carets in it represent different (but related) things . The function is composed of three parts: <code>^. ^: _1</code> . The first part, <code>^.</code>, is the primitive logarithm operator (e.g. <code>3 = 10^.1000</code>) .
Line 1,260 ⟶ 1,785:
Similarly, we can define exponentiation as the reverse of the inverse of root. That is, ''x pow y = y root<sup>-1</sup> x'':
 
<langsyntaxhighlight lang="j"> exp =: %:^:_1~
81 exp 0.5
9</langsyntaxhighlight>
 
Compare this with the previous definition: it is the same, except that <code>%:</code> , ''root'', has been substituted for <code>^.</code> , ''logarithm'', and the arguments have been reversed (or ''reflected'') with <code>~</code>.
Line 1,273 ⟶ 1,798:
Let's use Euler's famous formula, ''e<sup>pi*i</sup> = -1'' as an example:
 
<langsyntaxhighlight lang="j"> pi =: 3.14159265358979323846
e =: 2.71828182845904523536
i =: 2 %: _1 NB. Square root of -1
e^(pi*i)
_1</langsyntaxhighlight>
 
And, as stated, our redefinition is equivalent:
 
<langsyntaxhighlight lang="j"> exp =: %:^:_1~
e exp (pi*i)
_1</langsyntaxhighlight>
 
=={{header|Java}}==
Java does not support operator definition. This example is unoptimized, but will handle negative exponents as well. It is unnecessary to show int<sup>int</sup> since an int in Java will be cast as a double.
<langsyntaxhighlight lang="java">public class Exp{
public static void main(String[] args){
System.out.println(pow(2,30));
Line 1,302 ⟶ 1,827:
return ans;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,311 ⟶ 1,836:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function pow(base, exp) {
if (exp != Math.floor(exp))
throw "exponent must be an integer";
Line 1,322 ⟶ 1,847:
}
return ans;
}</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># 0^0 => 1
# NOTE: jq converts very large integers to floats.
# This implementation uses reduce to avoid deep recursion
Line 1,339 ⟶ 1,864:
end
else error("This is a toy implementation that requires n be integral")
end ;</langsyntaxhighlight>
Demonstration:<langsyntaxhighlight lang="jq">def demo(x;y):
x | [ power_int(y), (log*y|exp) ] ;
 
Line 1,353 ⟶ 1,878:
[2.4328178969536854e+42, 2.4328178969536693e+42]
[4.1104597317052596e-43, 4.1104597317052874e-43]
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
function pow(base::Number, exp::Integer)
r = one(base)
Line 1,364 ⟶ 1,889:
return r
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,381 ⟶ 1,906:
=={{header|Kotlin}}==
Kotlin does not have a dedicated exponentiation operator (we would normally use Java's Math.pow method instead) but it's possible to implement integer and floating power exponentiation (with integer exponents) using infix extension functions which look like non-symbolic operators for these actions:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
infix fun Int.ipow(exp: Int): Int =
when {
this == 1 -> 1
this == -1 -> if (exp %and 21 == 0) 1 else -1
exp < 0 -> throw IllegalArgumentException("invalid exponent")
exp == 0 -> 1
Line 1,393 ⟶ 1,918:
var base = this
var e = exp
while (e > 01) {
if (e and 1 == 1) ans *= base
e = e shr 1
base *= base
}
ans * base
}
}
Line 1,423 ⟶ 1,948:
println("1.5 ^ 0 = ${1.5 dpow 0}")
println("4.5 ^ 2 = ${4.5 dpow 2}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,435 ⟶ 1,960:
4.5 ^ 2 = 20.25
</pre>
 
=={{header|Lambdatalk}}==
 
Following the example given in Scheme
 
<syntaxhighlight lang="scheme">
{def ^
{def *^
{lambda {:base :exponent :acc}
{if {= :exponent 0}
then :acc
else {*^ :base {- :exponent 1} {* :acc :base}}}}}
{lambda {:base :exponent}
{*^ :base :exponent 1}}}
-> ^
 
{^ 2 3}
-> 8
{^ {/ 1 2} 3}
-> 0.125 // No rational type as primitives
{^ 0.5 3}
-> 0.125
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print " 11^5 = ", floatPow( 11, 5 )
print " (-11)^5 = ", floatPow( -11, 5 )
Line 1,463 ⟶ 2,011:
floatPow =m
end function
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
Lingo doesn't support user-defined operators.
<langsyntaxhighlight lang="lingo">-- As for built-in power() function:
-- base can be either integer or float; returns float.
on pow (base, exp)
Line 1,480 ⟶ 2,028:
end repeat
return res
end</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Lua}}==
All numbers in Lua are floating point numbers (thus, there are no real integers). Operator overloading is supported for tables only.
<langsyntaxhighlight lang="lua">number = {}
 
function number.pow( a, b )
Line 1,516 ⟶ 2,064:
x = number.New( 5 )
print( x^2 ) --> 25
print( number.pow( x, -4 ) ) --> 0.016</langsyntaxhighlight>
 
=={{header|Lucid}}==
[http://portal.acm.org/citation.cfm?id=947727.947728&coll=GUIDE&dl=GUIDE Some misconceptions about Lucid]
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Exponentiation {
\\ a variable can be any type except a string (no $ in name)
\\ variable b is long type.
\\ by default we pass by value arguments to a function
\\ to pass by reference we have to use & before name,
\\ in the signature and in the call
function pow(a, b as long) {
p=a-a ' make p same type as a
p++
if b>0 then for i=1& to b {p*=a}
=p
}
const fst$="{0::-32} {1}"
Document exp$
k= pow(11&, 5)
exp$=format$(fst$, k, type$(k)="Long")+{
}
l=pow(11, 5)
exp$=format$(fst$, l, type$(l)="Double")+{
}
m=pow(pi, 3)
exp$=format$(fst$, m, type$(m)="Decimal")+{
}
\\ send to clipboard
clipboard exp$
\\ send monospaced type text to console using cr char to change lines
Print #-2, exp$
Rem Report exp$ ' send to console using proportional spacing and justification
}
Exponentiation
 
 
</syntaxhighlight>
 
{{out}}
<pre>
161051 True
161051 True
31.006276680299820175476315064 True
 
</pre >
 
=={{header|M4}}==
M4 lacks floating point computation and operator definition.
<langsyntaxhighlight M4lang="m4">define(`power',`ifelse($2,0,1,`eval($1*$0($1,decr($2)))')')
power(2,10)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,539 ⟶ 2,131:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Define a function and an infix operator \[CirclePlus] with the same definition:
<langsyntaxhighlight Mathematicalang="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]</langsyntaxhighlight>
Examples:
<langsyntaxhighlight Mathematicalang="mathematica">exponentiation[1.23,3]
exponentiation[4,0]
exponentiation[2.5,-2]
1.23\[CirclePlus]3
4\[CirclePlus]0
2.5\[CirclePlus]-2</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">1.86087
1
0.16
1.86087
1
0.16</langsyntaxhighlight>
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.
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">"^^^"(a, n) := block(
[p: 1],
while n > 0 do (
Line 1,574 ⟶ 2,166:
 
2.5 ^^^ 10;
9536.7431640625</langsyntaxhighlight>
 
=={{header|MiniScript}}==
{{trans|Wren}}
MiniScript's built-in exponentiation operator is '^' which works for both integer and fractional bases and exponents. The language only has one number type whose underlying representation is a 64-bit float.
<syntaxhighlight lang="miniscript">import "qa"
 
number.isInteger = function
return self == floor(self)
end function
 
ipow = function(base, exp)
if not base.isInteger then qa.abort("ipow must have an integer base")
if not exp.isInteger then qa.abort("ipow must have an integer exponent")
if base == 1 or exp == 0 then return 1
if base == -1 then
if exp%2 == 0 then return 1
return -1
end if
if exp < 0 then qa.abort("ipow cannot have a negative exponent")
ans = 1
e = exp
while e > 1
if e%2 == 1 then ans *= base
e = floor(e/2)
base *= base
end while
return ans * base
end function
 
fpow = function(base, exp)
if not exp.isInteger then qa.abort("fpow must have an integer exponent")
ans = 1.0
e = exp
if e < 0 then
base = 1 / base
e = -e
end if
while e > 0
if e%2 == 1 then ans *= base
e = floor(e/2)
base *= base
end while
return ans
end function
 
print "Using the reimplemented functions:"
print " 2 ^ 3 = " + ipow(2, 3)
print " 1 ^ -10 = " + ipow(1, -10)
print " -1 ^ -3 = " + ipow(-1, -3)
print
print " 2.0 ^ -3 = " + fpow(2.0, -3)
print " 1.5 ^ 0 = " + fpow(1.5, 0)
print " 4.5 ^ 2 = " + fpow(4.5, 2)
print
print "Using the ^ operator:"
print " 2 ^ 3 = " + 2 ^ 3
print " 1 ^ -10 = " + 1 ^ (-10)
print " -1 ^ -3 = " + (-1) ^ (-3)
print
print " 2.0 ^ -3 = " + 2.0 ^ (-3)
print " 1.5 ^ 0 = " + 1.5 ^ 0
print " 4.5 ^ 2 = " + 4.5 ^ 2</syntaxhighlight>
 
{{out}}
<pre>Using the reimplemented functions:
2 ^ 3 = 8
1 ^ -10 = 1
-1 ^ -3 = -1
 
2.0 ^ -3 = 0.125
1.5 ^ 0 = 1
4.5 ^ 2 = 20.25
 
Using the ^ operator:
2 ^ 3 = 8
1 ^ -10 = 1
-1 ^ -3 = -1
 
2.0 ^ -3 = 0.125
1.5 ^ 0 = 1
4.5 ^ 2 = 20.25</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">С/П x^y С/П</langsyntaxhighlight>
 
=={{header|Modula-2}}==
Whilst some implementations or dialects of Modula-2 may permit definition or overloading of operators, neither is permitted in N.Wirth's classic language definition and the ISO Modula-2 standard. The operations are therefore given as library functions.
<langsyntaxhighlight lang="modula2">
(* Library Interface *)
DEFINITION MODULE Exponentiation;
Line 1,628 ⟶ 2,301:
 
END Exponentiation.
</syntaxhighlight>
</lang>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Expt EXPORTS Main;
 
IMPORT IO, Fmt;
Line 1,662 ⟶ 2,335:
IO.Put("2 ^ 4 = " & Fmt.Int(IntExpt(2, 4)) & "\n");
IO.Put("2.5 ^ 4 = " & Fmt.Real(RealExpt(2.5, 4)) & "\n");
END Expt.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,671 ⟶ 2,344:
=={{header|Nemerle}}==
Macros can be used to define a new operator:
<langsyntaxhighlight Nemerlelang="nemerle">using System;
 
macro @^ (val, pow : int)
{
<[ Math.Pow($val, $pow) ]>
}</langsyntaxhighlight>
The file with the macro needs to be compiled as a library, and the resulting assembly must be referenced when compiling source files which use the operator.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Assertions;
Line 1,719 ⟶ 2,392:
WriteLine($"$eight, $four, $four_d");
}
}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc `^`[T: float|int](base: T; exp: int): T =
var (base, exp) = (base, exp)
result = 1
Line 1,744 ⟶ 2,417:
echo "2^-6 = ", 2 ^ -6
echo "2.71^6 = ", 2.71^6
echo "2.71^-6 = ", 2.71 ^ -6</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Exp {
function : Main(args : String[]) ~ Nil {
Pow(2,30)->PrintLine();
Line 1,767 ⟶ 2,440:
return ans;
}
}</langsyntaxhighlight>
 
<pre>1.07374182e+009
Line 1,778 ⟶ 2,451:
used:
 
<langsyntaxhighlight lang="ocaml">let pow one mul a n =
let rec g p x = function
| 0 -> x
Line 1,802 ⟶ 2,475:
 
See http://en.wikipedia.org/wiki/Thue-Morse_sequence
*)</langsyntaxhighlight>
 
See also [[Matrix-exponentiation operator#OCaml]] for a matrix usage.
Line 1,810 ⟶ 2,483:
This function works either for int or floats :
 
<langsyntaxhighlight Oforthlang="oforth">: powint(r, n)
| i |
1 n abs loop: i [ r * ]
Line 1,818 ⟶ 2,491:
2 powint(3) println
1.2 4 powint println
1.2 powint(4) println</langsyntaxhighlight>
 
{{out}}
Line 1,830 ⟶ 2,503:
=={{header|PARI/GP}}==
This version works for integer and floating-point bases (as well as intmod bases, ...).
<langsyntaxhighlight lang="parigp">ex(a, b)={
my(c = 1);
while(b > 1,
Line 1,838 ⟶ 2,511:
);
a * c
};</langsyntaxhighlight>
 
PARI/GP also has a built-in operator that works for any type of numerical exponent:
<langsyntaxhighlight lang="parigp">ex2(a, b) = a ^ b;</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program ExponentiationOperator(output);
 
function intexp (base, exponent: integer): longint;
Line 1,881 ⟶ 2,554:
writeln('2^30: ', intexp(2, 30));
writeln('2.0^30: ', realexp(2.0, 30));
end.</langsyntaxhighlight>
{{out}}
<pre>% ./ExponentiationOperator
Line 1,933 ⟶ 2,606:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl -w
use strict ;
 
Line 1,959 ⟶ 2,632:
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" ;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,969 ⟶ 2,642:
 
The following version is simpler and much faster for large exponents, since it uses exponentiation by squaring.
<langsyntaxhighlight Perllang="perl">sub ex {
my($base,$exp) = @_;
die "Exponent '$exp' must be an integer!" if $exp != int($exp);
Line 1,981 ⟶ 2,654:
}
$base * $c;
}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2018.03}}
 
<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 }
 
# Testing
 
say pow .75, -5;
say .75 *** -5;</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
The builtin power function handles atoms and integers for both arguments, whereas this deliberately restricts the exponent to an integer.<br>
There is no operator overloading in Phix, or for that matter any builtin overriding.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function powi(atom b, integer i)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
atom v=1
<span style="color: #008080;">function</span> <span style="color: #000000;">powir</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
b = iff(i<0 ? 1/b : b)
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
i = abs(i)
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
while i>0 do
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span> <span style="color: #008080;">do</span>
if and_bits(i,1) then v *= b end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">b</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
b *= b
<span style="color: #000000;">b</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">b</span>
i = floor(i/2)
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return v
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?powi(-3,-5)
<span style="color: #0000FF;">?</span><span style="color: #000000;">powir</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
?power(-3,-5)</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,023 ⟶ 2,683:
=={{header|PicoLisp}}==
This uses Knuth's algorithm (The Art of Computer Programming, Vol. 2, page 442)
<langsyntaxhighlight PicoLisplang="picolisp">(de ** (X N) # N th power of X
(if (ge0 N)
(let Y 1
Line 2,032 ⟶ 2,692:
Y )
(setq X (* X X)) ) )
0 ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">declare exp generic
(iexp when (fixed, fixed),
fexp when (float, fixed) );
Line 2,057 ⟶ 2,717:
end;
return (exp);
end fexp;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function pow($a, [int]$b) {
if ($b -eq -1) { return 1/$a }
if ($b -eq 0) { return 1 }
Line 2,079 ⟶ 2,739:
return $result
}
}</langsyntaxhighlight>
The function works for both integers and floating-point values as first argument.
 
Line 2,094 ⟶ 2,754:
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 <code>double</code>, but then the return type would be always double while currently <code>pow 2 3</code> returns an <code>int</code>.
 
=={{header|PureBasic}}==
PureBasic does not allow an operator to be redefined or operator overloading.
<lang PureBasic>Procedure powI(base, exponent)
Protected i, result.d
If exponent < 0
If base = 1
result = 1
EndIf
ProcedureReturn result
EndIf
result = 1
For i = 1 To exponent
result * base
Next
ProcedureReturn result
EndProcedure
Procedure.f powF(base.f, exponent)
Protected i, magExponent = Abs(exponent), result.d
If base <> 0
result = 1.0
If exponent <> 0
For i = 1 To magExponent
result * base
Next
If exponent < 0
result = 1.0 / result
EndIf
EndIf
EndIf
ProcedureReturn result
EndProcedure
 
If OpenConsole()
Define x, a.f, exp
x = Random(10) - 5
a = Random(10000) / 10000 * 10
For exp = -3 To 3
PrintN(Str(x) + " ^ " + Str(exp) + " = " + Str(powI(x, exp)))
PrintN(StrF(a) + " ^ " + Str(exp) + " = " + StrF(powF(a, exp)))
PrintN("--------------")
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</lang>
{{out}}
<pre>-3 ^ -3 = 0
6.997000 ^ -3 = 0.002919
--------------
-3 ^ -2 = 0
6.997000 ^ -2 = 0.020426
--------------
-3 ^ -1 = 0
6.997000 ^ -1 = 0.142918
--------------
-3 ^ 0 = 1
6.997000 ^ 0 = 1.000000
--------------
-3 ^ 1 = -3
6.997000 ^ 1 = 6.997000
--------------
-3 ^ 2 = 9
6.997000 ^ 2 = 48.958012
--------------
-3 ^ 3 = -27
6.997000 ^ 3 = 342.559235
-------------</pre>
 
 
=={{header|Prolog}}==
Line 2,182 ⟶ 2,770:
The predicate <code>is/2</code> supports functional syntax in its second argument: e.g., <code>X is sqrt(2) + 1</code>. New arithmetic functions can be added with the `arithmetic_function/1` directive, wherein the arity attributed to the function is one less than the arity of the predicate which will be called during term expansion and evaluation. The following directives establish <code>^^/2</code> as, first, an arithmetic function, and then as a right-associative binary operator (so that <code>X is 2^^2^^2</code> == ''X = 2^(2^2)</code>):
 
<langsyntaxhighlight lang="prolog">:- arithmetic_function((^^)/2).
:- op(200, xfy, user:(^^)).</langsyntaxhighlight>
 
When <code>^^/2</code> occurs in an expression in the second argument of <code>is/2</code>, Prolog calls the subsequently defined predicate <code>^^/3</code>, and obtains the operators replacement value from the predicate's third argument.
Line 2,191 ⟶ 2,779:
This solution employs the higher-order predicate <code>foldl/4</code> from the standard SWI-Prolog <code>library(apply)</code>, in conjunction with an auxiliary "folding predicate" (note, the definition uses the <code>^^</code> operator as an arithmetic function):
 
<langsyntaxhighlight lang="prolog">%% ^^/3
%
% True if Power is Base ^ Exp.
Line 2,214 ⟶ 2,802:
 
exp_folder(Base, Power, Powers, Power) :-
Power is Base * Powers.</langsyntaxhighlight>
 
'''Example usage:'''
 
<langsyntaxhighlight lang="prolog">?- X is 2 ^^ 3.
X = 8.
 
Line 2,228 ⟶ 2,816:
 
?- X is 2.5 ^^ 3.
X = 15.625.</langsyntaxhighlight>
 
=== Recursive Predicate ===
Line 2,234 ⟶ 2,822:
An implementation of exponentiation using recursion and no control predicates.
 
<langsyntaxhighlight lang="prolog">exp_recursive(Base, NegExp, NegPower) :-
NegExp < 0,
Exp is NegExp * -1,
Line 2,249 ⟶ 2,837:
NewAcc is Base * Acc,
NewExp is Exp - 1,
exp_recursive_(Base, NewExp, NewAcc, Power).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
PureBasic does not allow an operator to be redefined or operator overloading.
<syntaxhighlight lang="purebasic">Procedure powI(base, exponent)
Protected i, result.d
If exponent < 0
If base = 1
result = 1
EndIf
ProcedureReturn result
EndIf
result = 1
For i = 1 To exponent
result * base
Next
ProcedureReturn result
EndProcedure
Procedure.f powF(base.f, exponent)
Protected i, magExponent = Abs(exponent), result.d
If base <> 0
result = 1.0
If exponent <> 0
For i = 1 To magExponent
result * base
Next
If exponent < 0
result = 1.0 / result
EndIf
EndIf
EndIf
ProcedureReturn result
EndProcedure
 
If OpenConsole()
Define x, a.f, exp
x = Random(10) - 5
a = Random(10000) / 10000 * 10
For exp = -3 To 3
PrintN(Str(x) + " ^ " + Str(exp) + " = " + Str(powI(x, exp)))
PrintN(StrF(a) + " ^ " + Str(exp) + " = " + StrF(powF(a, exp)))
PrintN("--------------")
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</syntaxhighlight>
{{out}}
<pre>-3 ^ -3 = 0
6.997000 ^ -3 = 0.002919
--------------
-3 ^ -2 = 0
6.997000 ^ -2 = 0.020426
--------------
-3 ^ -1 = 0
6.997000 ^ -1 = 0.142918
--------------
-3 ^ 0 = 1
6.997000 ^ 0 = 1.000000
--------------
-3 ^ 1 = -3
6.997000 ^ 1 = 6.997000
--------------
-3 ^ 2 = 9
6.997000 ^ 2 = 48.958012
--------------
-3 ^ 3 = -27
6.997000 ^ 3 = 342.559235
-------------</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">MULTIPLY = lambda x, y: x*y
 
class num(float):
Line 2,266 ⟶ 2,925:
# works with floats as function or operator
print num(2.3).__pow__(8)
print num(2.3) ** 8</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Quackery does not have Float, but does have a library of Bignum Rationals.
 
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!
forward is ** ( n n --> n )
[ dup 1 < iff
[ 2drop 1 ] done
dup 1 & iff
[ 1 - dip dup ** * ]
else
[ 1 >> dip [ dup * ]
** ] ] resolves ** ( n n --> n )
 
forward is (v**) ( n/d n --> n/d )
 
[ dup 0 = iff
[ drop 2drop 1 n->v ]
done
dup 1 & iff
[ 1 - dip 2dup (v**)
v* ]
else
[ 1 >>
dip [ 2dup v* ]
(v**) ] ] resolves (v**) ( n/d n --> n/d )
[ dup 0 < iff
[ abs (v**) 1/v ]
else (v**) ] is v** ( n/d n --> n/d )
say "The 10th power of 2 is: "
2 10 ** echo cr cr
say "The -10th power of 2.5 is: "
$ "2.5" $->v drop -10 v** 20 point$ echo$</syntaxhighlight>
 
{{out}}
 
<pre>The 10th power of 2 is: 1024
 
The -10th power of 2.5 is: 0.0001048576</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="r"># Method
pow <- function(x, y)
{
Line 2,280 ⟶ 2,984:
 
pow(3, 4) # 81
2.5 %pow% 2 # 6.25</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (^ base expt)
(for/fold ((acum 1))
Line 2,290 ⟶ 2,994:
 
(^ 5 2) ; 25
(^ 5.0 2) ; 25.0</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2023.09}}
 
<syntaxhighlight lang="raku" line>proto pow (Real, Int --> Real) {*}
multi pow (0, 0) { fail '0**0 is undefined' }
multi pow ($base, UInt $exp) { [*] $base xx $exp }
multi pow ($base, $exp) { 1 / samewith $base, -$exp }
 
multi infix:<**> (Real $a, Int $b) { pow $a, $b }
 
# Testing
 
say pow .75, -5;
say .75 ** -5;</syntaxhighlight>
 
=={{header|Retro}}==
Line 2,297 ⟶ 3,017:
From the '''math'''' vocabulary:
 
<langsyntaxhighlight Retrolang="retro">: pow ( bp-n ) 1 swap [ over * ] times nip ;</langsyntaxhighlight>
 
And in use:
 
<syntaxhighlight lang Retro="retro">2 5 ^math'pow</langsyntaxhighlight>
 
The fast exponentiation algorithm can be coded as follows:
 
<langsyntaxhighlight Retrolang="retro">: pow ( n m -- n^m )
1 2rot
[ dup 1 and 0 <>
Line 2,311 ⟶ 3,031:
[ dup * ] dip 1 >> dup 0 <>
] while
drop drop ;</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 1 with error checking===
The &nbsp; '''iPow''' &nbsp; function doesn't care what kind of number is to be raised to a power,
<br>it can be an integer or floating point number.
 
Extra error checking was added to verify that the invocation is syntactically correct.
<langsyntaxhighlight lang="rexx">/*REXX program computes and displays various (integer) exponentiations. */
say center('digits='digits(), 79, "─")
say 'iPow(17**65, 65) is:'
say iPow(17**, 65)
say
 
say 'iPow(0, -3) is:'
numeric digits 100; say center('digits='digits(), 79, "─")
say '17**65 iPow(0, is:'-3)
say 17**65
say
 
say 'iPow(8, 0) is:'
numeric digits 10; say center('digits='digits(), 79, "─")
say '2 **iPow(8, -10 is:'0)
say 2 ** -10
say
 
numeric digits 3012; say center('digits='digits(), 79, "─")
say 'iPow(2, -3.1415926535897932384626433 ** 310) is:'
say iPow(2, -10)
say -3.1415926535897932384626433 ** 3
say
 
numeric digits 100030; say center('digits='digits(), 79, "─")
say '2 ** 1000iPow(-3.1415926535897932384626433, 3) is:'
say iPow(-3.1415926535897932384626433, 3)
say 2 ** 1000
say
 
Line 2,347 ⟶ 3,066:
say 'iPow(5, 70) is:'
say iPow(5, 70)
say
 
numeric digits 100; say center('digits='digits(), 79, "─")
say 'iPow(17, 65) is:'
say iPow(17, 65)
say
 
numeric digits 1000; say center('digits='digits(), 79, "─")
say 'iPow(2, 1000) is:'
say iPow(2, 1000)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
errMsg: say; say '***error***'; say; say arg(1); say; say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
iPow: procedure; parse arg x 1 _,p; #args= arg() /*_: is a copy of X. */
if arg()#args<2 then call errMsg "not enough arguments specified"
if arg()#args>2 then call errMsg "too many arguments specified"
if \datatype(x, 'N') then call errMsg "1st arg isn't numeric:" x
if \datatype(p, 'W') then call errMsg "2nd arg isn't an integer:" p
if p=0 then return 1 /*handle powers of zero. */
if x=0 | x=1 do abs(p) - 1; then return _=_*x; end /*abs(p)-1handle special cases. */
if p<0 do abs(p) - 1; then _=1/ _ * x; end /*perform exponentiation */
if p<0 then _= 1 / _ /*process its reciprocal.*/
return _</lang>
return _</syntaxhighlight>
;;;output'''
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
───────────────────────────────────digits=9────────────────────────────────────
iPow(17**65, 65) is:
9.53190909E53190906E+79
 
iPow(0, -3) is:
──────────────────────────────────digits=100───────────────────────────────────
0
17**65 is:
95319090450218007303742536355848761234066170796000792973413605849481890760893457
 
iPow(8, 0) is:
───────────────────────────────────digits=10───────────────────────────────────
1
2 ** -10 is:
 
───────────────────────────────────digits=12───────────────────────────────────
iPow(2, -10) is:
0.0009765625
 
───────────────────────────────────digits=30───────────────────────────────────
iPow(-3.1415926535897932384626433 **, 3) is:
-31.0062766802998201754763126013
 
──────────────────────────────────digits=1000──────────────────────────────────
2 ** 1000 is:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
 
───────────────────────────────────digits=60───────────────────────────────────
ipowiPow(5, 70) is:
8470329472543003390683225006796419620513916015625
 
──────────────────────────────────digits=100───────────────────────────────────
iPow(17, 65) is:
95319090450218007303742536355848761234066170796000792973413605849481890760893457
 
──────────────────────────────────digits=1000──────────────────────────────────
iPow(2, 1000) is:
107150860718626732094842504906000181056140481170553360744375038837035105112493612249319837881569585812759467291755314682
518714528569231404359845775746985748039345677748242309854210746050623711418779541821530464749835819412673987675591655439
46077062914571196477686542167660429831652624386837205668069376
</pre>
 
===version 2===
An alternative to ipow that is about 30% faster (for 5**70) would be.
 
However, for single digit powers, version 2 is around 300% slower than version 1.
<syntaxhighlight lang="rexx">pp: Procedure
Parse Arg x,y
If x=0 & y<0 Then call errMsg x"**" y "is invalid"
yp=abs(y)
p.1=x
x.1=1
i=1
Do k=2 By 1 While i<=yp%2
i=2*i
kk=k-1
p.k=p.kk*p.kk
x.k=i
/* Say k i x.k p.k */
End
pp=1
Do i=k-1 To 1 By -1
If x.i<=yp Then Do
pp=pp*p.i
yp=yp-x.i
End
End
If y<0 Then
pp=1/pp
Return pp
</syntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "11^5 = " + ipow(11, 5) + nl
see "pi^3 = " + fpow(3.14, 3) + nl
Line 2,409 ⟶ 3,177:
next
return p
</syntaxhighlight>
</lang>
Output :
<pre>
11^5 = 161051
pi^3 = 30.96
</pre>
 
=={{header|RPL}}==
RPL cannot overload operators, but new functions can be added, making no difference in usage from operators because of the postfix syntax. RPL advocates that functions and operators should be able to handle many types of data - including unsigned integers and floating point numbers - with the same methods, making the code compact and versatile and making it easier to remember commands. The one-line program below can exponentiate real and complex numbers, but also matrices.
≪ '''IF''' DUP NOT '''THEN''' DROP DUP TYPE 3 == SWAP IDN 1 IFTE '''ELSE''' 1 1 ROT '''START''' OVER * '''NEXT''' SWAP DROP '''END''' ≫ ‘'''POWER'''’ STO
 
25.2 3 '''POWER'''
#25d 3 '''POWER'''
-25 3 '''POWER'''
(2,5) 3 '''POWER'''
[[ 1 2 ][ 3 4 ]] 3 '''POWER'''
{{out}}
<pre>
5: 16003.008
4: # 15625d
3: -15625
2: (-142,-65)
1: [[ 37 54 ][ 81 118 ]]
</pre>
 
Line 2,419 ⟶ 3,205:
We add a <tt>pow</tt> method to <tt>Numeric</tt> objects. To calculate <tt>5.pow 3</tt>, this method fills an array <tt>[5, 5, 5]</tt> and then multiplies together the elements.
 
<langsyntaxhighlight lang="ruby">class Numeric
def pow(m)
raise TypeError, "exponent must be an integer: #{m}" unless m.is_a? Integer
Line 2,429 ⟶ 3,215:
p 5.pow(3)
p 5.5.pow(3)
p 5.pow(3.1)</langsyntaxhighlight>
 
{{out}}
Line 2,440 ⟶ 3,226:
 
To overload the ** exponentiation operator, this might work, but doesn't:
<langsyntaxhighlight lang="ruby">class Numeric
def **(m)
pow(m)
end
end</langsyntaxhighlight>
It doesn't work because the ** method is defined independently for Numeric subclasses Fixnum, Bignum and Float. One must:
<langsyntaxhighlight lang="ruby">class Fixnum
def **(m)
print "Fixnum "
Line 2,467 ⟶ 3,253:
p i=2**64
p i ** 2
p 2.2 ** 3</langsyntaxhighlight>
{{out}}
<pre>Fixnum pow!!
Line 2,477 ⟶ 3,263:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print " 11^5 = ";11^5
print " (-11)^5 = ";-11^5
print " 11^( -5) = ";11^-5
Line 2,483 ⟶ 3,269:
print " 0^2 = ";0^2
print " 2^0 = ";2^0
print " -2^0 = ";-2^0</langsyntaxhighlight>
{{out}}
<pre> 11^5 = 161051
Line 2,492 ⟶ 3,278:
2^0 = 1
-2^0 = 1</pre>
 
=={{header|Rust}}==
The <code>num</code> crate is the de-facto Rust library for numerical generics and it provides the <code>One</code> trait which allows for an exponentiation function that is generic over both integral and floating point types. The library provides this generic exponentiation function, the implementation of which is the <code>pow</code> function below.
<langsyntaxhighlight lang="rust">extern crate num;
use num::traits::One;
use std::ops::Mul;
Line 2,517 ⟶ 3,304:
}
acc
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,525 ⟶ 3,312:
 
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.
<langsyntaxhighlight lang="scala">object Exponentiation {
import scala.annotation.tailrec
Line 2,567 ⟶ 3,354:
implicit def toExponent(n: Double): ExponentF[Double] = new ExponentF(n)
}
}</langsyntaxhighlight>Functions powI and powF above are not tail recursive, since the result of the recursive call is multiplied by n. A tail recursive version of powI would be:
<langsyntaxhighlight lang="scala"> @tailrec def powI[N](n: N, exponent: Int, acc:Int=1)(implicit num: Integral[N]): N = {
exponent match {
case 0 => acc
Line 2,574 ⟶ 3,361:
case _ => powI(n, (exponent - 1), acc*n)
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
This definition of the exponentiation procedure <code>^</code> operates on bases of all numerical types that the multiplication procedure <code>*</code> 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.
<langsyntaxhighlight lang="scheme">(define (^ base exponent)
(define (*^ exponent acc)
(if (= exponent 0)
Line 2,592 ⟶ 3,379:
(newline)
(display (^ 2+i 3))
(newline)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,611 ⟶ 3,398:
Instead the exponentiation-by-squaring algorithm is used.
 
<langsyntaxhighlight lang="seed7">const func integer: intPow (in var integer: base, in var integer: exponent) is func
result
var integer: result is 0;
Line 2,632 ⟶ 3,419:
end while;
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#intPow]
 
<langsyntaxhighlight lang="seed7">const func float: fltIPow (in var float: base, in var integer: exponent) is func
result
var float: power is 1.0;
Line 2,667 ⟶ 3,454:
end if;
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fltIPow]
Line 2,676 ⟶ 3,463:
and [http://seed7.sourceforge.net/libraries/float.htm float] bases:
 
<langsyntaxhighlight lang="seed7">$ syntax expr: .(). ^* .() is <- 4;
 
const func integer: (in var integer: base) ^* (in var integer: exponent) is
Line 2,682 ⟶ 3,469:
 
const func float: (in var float: base) ^* (in var integer: exponent) is
return fltIPow(base, exponent);</langsyntaxhighlight>
 
=={{header|Sidef}}==
Function definition:
<langsyntaxhighlight lang="ruby">func expon(_, {.is_zero}) { 1 }
 
func expon(base, exp {.is_neg}) {
Line 2,705 ⟶ 3,492:
 
say expon(3, 10)
say expon(5.5, -3)</langsyntaxhighlight>
 
Operator definition:
<langsyntaxhighlight lang="ruby">class Number {
method ⊙(exp) {
expon(self, exp)
Line 2,715 ⟶ 3,502:
 
say (3 ⊙ 10)
say (5.5 ⊙ -3)</langsyntaxhighlight>
{{out}}
<pre>
59049
0.0060105184072126220886551465063861758076634109692
0.006010518407212622088655146506386175807661607813673929376408715251690458302028550142749812171299774605559729526671675432
</pre>
 
=={{header|Slate}}==
This code is from the current slate implementation:
<langsyntaxhighlight lang="slate">x@(Number traits) raisedTo: y@(Integer traits)
[
y isZero ifTrue: [^ x unit].
Line 2,742 ⟶ 3,529:
result]
ifFalse: [(x raisedTo: y negated) reciprocal]
].</langsyntaxhighlight>
 
For floating numbers:
 
<langsyntaxhighlight 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."
Line 2,753 ⟶ 3,540:
x isZero \/ [y isUnit] ifTrue: [^ x].
(x ln * y) exp
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
''Extending'' the class Number, we provide the operator for integers, floating points, ''rationals'' numbers (and any other derived class)
<langsyntaxhighlight lang="smalltalk">Number extend [
** anInt [
| r |
Line 2,772 ⟶ 3,560:
( 2.5 ** 3 ) displayNl.
( 2 ** 10 ) displayNl.
( 3/7 ** 3 ) displayNl.</langsyntaxhighlight>
 
{{out}}
Line 2,781 ⟶ 3,569:
=={{header|Standard ML}}==
The following operators only take nonnegative integer exponents.
<langsyntaxhighlight lang="sml">fun expt_int (a, b) = let
fun aux (x, i) =
if i = b then x
Line 2,800 ⟶ 3,588:
infix 6 **
val op *** = expt_real
infix 6 ***</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sml">- 2 ** 3;
val it = 8 : int
- 2.4 *** 3;
val it = 13.824 : real</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">mata
function pow(a, n) {
x = a
Line 2,817 ⟶ 3,605:
return(p)
}
end</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|Python}}
Defines generic function raise(_:to:) and operator ** that will work with all bases conforming to protocol Numeric, including Float and Int.
<langsyntaxhighlight Swiftlang="swift">func raise<T: Numeric>(_ base: T, to exponent: Int) -> T {
precondition(exponent >= 0, "Exponent has to be nonnegative")
return Array(repeating: base, count: exponent).reduce(1, *)
Line 2,839 ⟶ 3,627:
assert(someFloat ** someInt == 1024)
assert(raise(someInt, to: someInt) == 10000000000)
assert(someInt ** someInt == 10000000000)</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 2,847 ⟶ 3,635:
 
This solution does not consider negative exponents.
<langsyntaxhighlight 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"}
Line 2,856 ⟶ 3,644:
expr {mypow(3, 3)} ;# ==> 27
expr {mypow(3.5, 3)} ;# ==> 42.875
expr {mypow(3.5, 3.2)} ;# ==> exponent must be an integer</langsyntaxhighlight>
 
=={{header|TI-57}}==
{| class="wikitable"
! Machine code
! Comment
|-
|
'''Lbl 9'''
STO 0
1
SUM 0
'''Lbl 1'''
INV Dsz
GTO 2
*
RCL 7
GTO 1
'''Lbl 2'''
=
'''R/S'''
RST
|
'''program power(t,x)''' // x is the display register
r0 = x
x = 1
r0 -= 1
loop
if --r0 = 0
exit loop
x *= t
end loop
return x
'''end program'''
reset pointer
|}
<code> 5 </code> <code>x⮂t</code> <code> 3 </code> <code>GTO</code> <code> 9 </code> <code>R/S</code>
{{out}}
<pre>
125.
</pre>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa"># these implementations ignore negative exponents
def intpow (int m, int n)
if (< n 1)
Line 2,882 ⟶ 3,712:
end for
return ret
end floatpow</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Function exp(ByVal base As Variant, ByVal exponent As Long) As Variant
Dim result As Variant
If TypeName(base) = "Integer" Or TypeName(base) = "Long" Then
Line 2,932 ⟶ 3,762:
Debug.Print "(-3.0)^(-4)=", exp(-3#, -4)
Debug.Print "0.0^(-4)=", exp(0#, -4)
End Sub</langsyntaxhighlight>{{out}}
<pre>Integer exponentiation
10^7= 10000000
Line 2,946 ⟶ 3,776:
(-3.0)^(-4)= 1,23456790123457E-02
0.0^(-4)= Fout 11</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function pow(x,y)
pow = 1
Line 2,971 ⟶ 3,802:
WScript.StdOut.Write "-3 ^ 5 = " & pow(-3,5)
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,980 ⟶ 3,811:
4 ^ -6 = 0.000244140625
-3 ^ 5 = -243
</pre>
 
=={{header|Wren}}==
Although Wren supports operator overloading, operators have to be instance methods and it is not possible to inherit from the built in Num class which already has a 'pow' method in any case.
 
I've therefore decided to implement the power functions as static methods of a Num2 class and then define the ''^'' operator for this class which calls these methods using its receiver and exponent as parameters.
<syntaxhighlight lang="wren">class Num2 {
static ipow(i, exp) {
if (!i.isInteger) Fiber.abort("ipow method must have an integer receiver")
if (!exp.isInteger) Fiber.abort("ipow method must have an integer exponent")
if (i == 1 || exp == 0) return 1
if (i == -1) return (exp%2 == 0) ? 1 : -1
if (exp < 0) Fiber.abort("ipow method cannot have a negative exponent")
var ans = 1
var base = i
var e = exp
while (e > 1) {
if (e%2 == 1) ans = ans * base
e = (e/2).floor
base = base * base
}
return ans * base
}
 
static fpow(f, exp) {
if (!exp.isInteger) Fiber.abort("fpow method must have an integer exponent")
var ans = 1.0
var e = exp
var base = (e < 0) ? 1/f : f
if (e < 0) e = -e
while (e > 0) {
if (e%2 == 1) ans = ans * base
e = (e/2).floor
base = base * base
}
return ans
}
 
construct new(n) { _n = n }
 
^(exp) {
if (_n.isInteger && (exp >= 0 || _n.abs == 1)) return Num2.ipow(_n, exp)
return Num2.fpow(_n, exp)
}
}
 
System.print("Using static methods:")
System.print(" 2 ^ 3 = %(Num2.ipow(2, 3))")
System.print(" 1 ^ -10 = %(Num2.ipow(1, -10))")
System.print(" -1 ^ -3 = %(Num2.ipow(-1, -3))")
System.print()
System.print(" 2.0 ^ -3 = %(Num2.fpow(2.0, -3))")
System.print(" 1.5 ^ 0 = %(Num2.fpow(1.5, 0))")
System.print(" 4.5 ^ 2 = %(Num2.fpow(4.5, 2))")
 
System.print("\nUsing the ^ operator:")
System.print(" 2 ^ 3 = %(Num2.new(2) ^ 3)")
System.print(" 1 ^ -10 = %(Num2.new(1) ^ -10)")
System.print(" -1 ^ -3 = %(Num2.new(-1) ^ -3)")
System.print()
System.print(" 2.0 ^ -3 = %(Num2.new(2.0) ^ -3)")
System.print(" 1.5 ^ 0 = %(Num2.new(1.5) ^ 0)")
System.print(" 4.5 ^ 2 = %(Num2.new(4.5) ^ 2)")</syntaxhighlight>
 
{{out}}
<pre>
Using static methods:
2 ^ 3 = 8
1 ^ -10 = 1
-1 ^ -3 = -1
 
2.0 ^ -3 = 0.125
1.5 ^ 0 = 1
4.5 ^ 2 = 20.25
 
Using the ^ operator:
2 ^ 3 = 8
1 ^ -10 = 1
-1 ^ -3 = -1
 
2.0 ^ -3 = 0.125
1.5 ^ 0 = 1
4.5 ^ 2 = 20.25
</pre>
 
Line 2,985 ⟶ 3,899:
To create an exponent operator you need to modify the compiler code,
which is open source.
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func real Power(X, Y); \X raised to the Y power; (X > 0.0)
Line 3,016 ⟶ 3,930:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,046 ⟶ 3,960:
Int and Float have pow methods and zkl doesn't allow you to add operators, classes can implement existing ones.
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn pow(n,exp){
reg v;
if(n.isType(1)){ // Int
Line 3,061 ⟶ 3,975:
}
v
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println("2^6 = %d".fmt(pow(2,6)));
println("2^-6 = %d".fmt(pow(2,-6)));
println("2.71^6 = %f".fmt(pow(2.71,6)));
println("2.71^-6 = %f".fmt(pow(2.71,-6)));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,079 ⟶ 3,993:
The function itself makes use of the inbuilt exponentiation operator, which is kind of cheating, but hey this provides a working implementation.
 
<langsyntaxhighlight lang="zxbasic">10 PRINT e(3,2): REM 3 ^ 2
20 PRINT e(1.5,2.7): REM 1.5 ^ 2.7
30 STOP
9950 DEF FN e(a,b)=a^b</langsyntaxhighlight>
 
The same string slicing trick used in [https://rosettacode.org/wiki/Factorial#ZX_Spectrum_Basic the recursive factorial function] can be used to come up with an integer solution; it works for any non-negative exponent. It's not recommended though; even the Spectrum's famously slow inbuilt exponentiation function is faster for exponents greater than 3. (A FOR-NEXT loop is fastest until about e=12.)
 
<syntaxhighlight lang="zxbasic">
9999 DEF FN e(m,e)=VAL "m*FN e(m,e-1)*1"((e<1)*12+1 TO )</syntaxhighlight>
9,476

edits