Exponentiation operator: Difference between revisions

Added MiniScript
m (Moved Wren entry into correct alphabetical order.)
(Added MiniScript)
 
(2 intermediate revisions by 2 users not shown)
Line 2,167:
2.5 ^^^ 10;
9536.7431640625</syntaxhighlight>
 
=={{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}}==
Line 3,425 ⟶ 3,506:
<pre>
59049
0.0060105184072126220886551465063861758076634109692
0.006010518407212622088655146506386175807661607813673929376408715251690458302028550142749812171299774605559729526671675432
</pre>
 
Line 3,733 ⟶ 3,814:
 
=={{header|Wren}}==
Although Wren supports operator overloading, operators have to be instance methods and it is not advisablepossible 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.
9,476

edits