RosettaCodeData/Task/Exponentiation-operator/MiniScript/exponentiation-operator.mini

59 lines
1.4 KiB
Plaintext

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