Exponentiation with infix operators in (or operating on) the base: Difference between revisions
Thundergnat (talk | contribs) →{{header|Raku}}: DRY |
Langurmonkey (talk | contribs) |
||
(34 intermediate revisions by 25 users not shown) | |||
Line 1: | Line 1: | ||
{{ |
{{task}} |
||
(Many programming languages, especially those with extended─precision integer arithmetic, usually |
(Many programming languages, especially those with extended─precision integer arithmetic, usually |
||
Line 27: | Line 27: | ||
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s). |
<small>(Not all computer programming languages have an exponential operator and/or support these syntax expression(s)</small>. |
||
Line 53: | Line 53: | ||
;Related tasks: |
;Related tasks: |
||
* [[ |
* [[Exponentiation order]] |
||
* [[ |
* [[Exponentiation operator]] |
||
* [[Arbitrary- |
* [[Arbitrary-precision integers (included)]] |
||
* [[ |
* [[Parsing/RPN to infix conversion]] |
||
* [[ |
* [[Operator precedence]] |
||
<br><br> |
<br><br> |
||
;References: |
;References: |
||
* [[wp:Order_of_operations#Programming_languages|Wikipedia: Order of operations in Programming languages]] |
|||
<br><br> |
<br><br> |
||
=={{header|Ada}}== |
|||
The order of precedence for Ada operators is: |
|||
<pre> |
|||
logical_operator ::= and | or | xor |
|||
relational_operator ::= = | /= | < | <= | > | >= |
|||
binary_adding_operator ::= + | – | & |
|||
unary_adding_operator ::= + | – |
|||
multiplying_operator ::= * | / | mod | rem |
|||
highest_precedence_operator ::= ** | abs | not |
|||
</pre> |
|||
Ada provides an exponentiation operator for integer types and floating point types. |
|||
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
|||
with Ada.Float_Text_IO; use Ada.Float_Text_IO; |
|||
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; |
|||
procedure Main is |
|||
ivalue : Integer := -5; |
|||
fvalue : float := -5.0; |
|||
begin |
|||
Put_Line("Integer exponentiation:"); |
|||
for i in 1..2 loop |
|||
for power in 2..3 loop |
|||
Put("x =" & ivalue'image & " p =" & power'image); |
|||
Put(" -x ** p "); |
|||
Put(item => -ivalue ** power, width => 4); |
|||
Put(" -(x) ** p "); |
|||
Put(item => -(ivalue) ** power, width => 4); |
|||
Put(" (-x) ** p "); |
|||
Put(Item => (- ivalue) ** power, Width => 4); |
|||
Put(" -(x ** p) "); |
|||
Put(Item => -(ivalue ** power), Width => 4); |
|||
New_line; |
|||
end loop; |
|||
ivalue := 5; |
|||
fvalue := 5.0; |
|||
end loop; |
|||
Put_Line("floating point exponentiation:"); |
|||
ivalue := -5; |
|||
fvalue := -5.0; |
|||
for i in 1..2 loop |
|||
for power in 2..3 loop |
|||
Put("x =" & fvalue'image & " p =" & power'image); |
|||
Put(" -x ** p "); |
|||
Put(item => -fvalue ** power, fore => 4, Aft => 1, Exp => 0); |
|||
Put(" -(x) ** p "); |
|||
Put(item => -(fvalue) ** power, fore => 4, Aft => 1, Exp => 0); |
|||
Put(" (-x) ** p "); |
|||
Put(Item => (- fvalue) ** power, fore => 4, Aft => 1, Exp => 0); |
|||
Put(" -(x ** p) "); |
|||
Put(Item => -(fvalue ** power), fore => 4, Aft => 1, Exp => 0); |
|||
New_line; |
|||
end loop; |
|||
ivalue := 5; |
|||
fvalue := 5.0; |
|||
end loop; |
|||
end Main; |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
Integer exponentiation: |
|||
x =-5 p = 2 -x ** p -25 -(x) ** p -25 (-x) ** p 25 -(x ** p) -25 |
|||
x =-5 p = 3 -x ** p 125 -(x) ** p 125 (-x) ** p 125 -(x ** p) 125 |
|||
x = 5 p = 2 -x ** p -25 -(x) ** p -25 (-x) ** p 25 -(x ** p) -25 |
|||
x = 5 p = 3 -x ** p -125 -(x) ** p -125 (-x) ** p -125 -(x ** p) -125 |
|||
floating point exponentiation: |
|||
x =-5.00000E+00 p = 2 -x ** p -25.0 -(x) ** p -25.0 (-x) ** p 25.0 -(x ** p) -25.0 |
|||
x =-5.00000E+00 p = 3 -x ** p 125.0 -(x) ** p 125.0 (-x) ** p 125.0 -(x ** p) 125.0 |
|||
x = 5.00000E+00 p = 2 -x ** p -25.0 -(x) ** p -25.0 (-x) ** p 25.0 -(x ** p) -25.0 |
|||
x = 5.00000E+00 p = 3 -x ** p -125.0 -(x) ** p -125.0 (-x) ** p -125.0 -(x ** p) -125.0 |
|||
</pre> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
In Algol 68, all unary operators have a higher precedence than any binary operator. |
In Algol 68, all unary operators have a higher precedence than any binary operator. |
||
<br>Algol 68 also allows UP and ^ for the exponentiation operator. |
<br>Algol 68 also allows UP and ^ for the exponentiation operator. |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
# show the results of exponentiation and unary minus in various combinations # |
# show the results of exponentiation and unary minus in various combinations # |
||
FOR x FROM -5 BY 10 TO 5 DO |
FOR x FROM -5 BY 10 TO 5 DO |
||
Line 74: | Line 149: | ||
print( ( " (-x)**p ", whole( (-x)**p, -4 ) ) ); |
print( ( " (-x)**p ", whole( (-x)**p, -4 ) ) ); |
||
print( ( " -(x**p) ", whole( -(x**p), -4 ) ) ); |
print( ( " -(x**p) ", whole( -(x**p), -4 ) ) ); |
||
print( ( newline ) ) |
print( ( newline ) ) |
||
OD |
OD |
||
OD |
OD |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 85: | Line 160: | ||
x = 5 p = 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125 |
x = 5 p = 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125 |
||
</pre> |
</pre> |
||
=={{header|AWK}}== |
|||
<syntaxhighlight lang="awk"> |
|||
# syntax: GAWK -f EXPONENTIATION_WITH_INFIX_OPERATORS_IN_OR_OPERATING_ON_THE_BASE.AWK |
|||
# converted from FreeBASIC |
|||
BEGIN { |
|||
print(" x p | -x^p -(x)^p (-x)^p -(x^p)") |
|||
print("--------+------------------------------------") |
|||
for (x=-5; x<=5; x+=10) { |
|||
for (p=2; p<=3; p++) { |
|||
printf("%3d %3d | %8d %8d %8d %8d\n",x,p,(-x^p),(-(x)^p),((-x)^p),(-(x^p))) |
|||
} |
|||
} |
|||
exit(0) |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
x p | -x^p -(x)^p (-x)^p -(x^p) |
|||
--------+------------------------------------ |
|||
-5 2 | -25 -25 25 -25 |
|||
-5 3 | 125 125 125 125 |
|||
5 2 | -25 -25 25 -25 |
|||
5 3 | -125 -125 -125 -125 |
|||
</pre> |
|||
=={{header|BASIC}}== |
|||
==={{header|Applesoft BASIC}}=== |
|||
<syntaxhighlight lang="gwbasic">S$=" ":M$=CHR$(13):?M$" X P -X^P -(X)^P (-X)^P -(X^P)":FORX=-5TO+5STEP10:FORP=2TO3:?M$MID$("+",1+(X<0));X" "PRIGHT$(S$+STR$(-X^P),8)RIGHT$(S$+STR$(-(X)^P),8)RIGHT$(S$+STR$((-X)^P),8)RIGHT$(S$+STR$(-(X^P)),8);:NEXTP,X</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
X P -X^P -(X)^P (-X)^P -(X^P) |
|||
-5 2 25 25 25 -25 |
|||
-5 3 125 125 125 125 |
|||
+5 2 25 25 25 -25 |
|||
+5 3 -125 -125 -125 -125 |
|||
</pre> |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="basic256">print " x p | -x^p -(x)^p (-x)^p -(x^p)" |
|||
print ("-"*15); "+"; ("-"*45) |
|||
for x = -5 to 5 step 10 |
|||
for p = 2 to 3 |
|||
print " "; rjust(x,2); " "; ljust(p,2); " | "; rjust((-x^p),6); " "; rjust((-(x)^p),6); (" "*6); rjust(((-x)^p),6); " "; rjust((-(x^p)),6) |
|||
next p |
|||
next x</syntaxhighlight> |
|||
{{out}} |
|||
<pre> x p | -x^p -(x)^p (-x)^p -(x^p) |
|||
---------------+--------------------------------------------- |
|||
-5 2 | -25.0 -25.0 25.0 -25.0 |
|||
-5 3 | 125.0 125.0 125.0 125.0 |
|||
5 2 | -25.0 -25.0 25.0 -25.0 |
|||
5 3 | -125.0 -125.0 -125.0 -125.0</pre> |
|||
==={{header|Gambas}}=== |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Print " x p | -x^p -(x)^p (-x)^p -(x^p)" |
|||
Print "----------------+---------------------------------------------" |
|||
For x As Integer = -5 To 5 Step 10 |
|||
For p As Integer = 2 To 3 |
|||
Print " "; Format$(x, "-#"); " "; Format$(p, "-#"); " | "; Format$((-x ^ p), "-###"); " "; Format$((-(x) ^ p), "-###"); " "; Format$(((-x) ^ p), "-###"); " "; Format$((-(x ^ p)), "-###") |
|||
Next |
|||
Next |
|||
End</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as FreeBASIC entry.</pre> |
|||
==={{header|QBasic}}=== |
|||
{{works with|QBasic|1.1}} |
|||
{{works with|QuickBasic|4.5}} |
|||
{{works with|FreeBASIC}} |
|||
<syntaxhighlight lang="qbasic">PRINT " x p | -x^p -(x)^p (-x)^p -(x^p)" |
|||
PRINT "----------------+---------------------------------------------" |
|||
FOR x = -5 TO 5 STEP 10 |
|||
FOR p = 2 TO 3 |
|||
PRINT USING " ## ## | #### #### #### ####"; x; p; (-x ^ p); (-(x) ^ p); ((-x) ^ p); (-(x ^ p)) |
|||
NEXT p |
|||
NEXT x</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as FreeBASIC entry.</pre> |
|||
==={{header|Run BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
{{works with|Liberty BASIC}} |
|||
{{works with|QBasic}} |
|||
{{works with|True BASIC}} |
|||
<syntaxhighlight lang="lb">print " x"; chr$(9); " p"; chr$(9); " | "; chr$(9); "-x^p"; chr$(9); " "; chr$(9); "-(x)^p"; chr$(9); " "; chr$(9); "(-x)^p"; chr$(9); " "; chr$(9); "-(x^p)" |
|||
print "----------------------------+-----------------------------------------------------------------" |
|||
for x = -5 to 5 step 10 |
|||
for p = 2 to 3 |
|||
print " "; x; chr$(9); " "; chr$(9); p; chr$(9); " | "; chr$(9); (-1*x^p); chr$(9); " "; chr$(9); (-1*(x)^p); chr$(9); " "; chr$(9); ((-1*x)^p); chr$(9); " "; chr$(9); (-1*(x^p)) |
|||
next p |
|||
next x |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Similar to FreeBASIC entry.</pre> |
|||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">PRINT " x p | -x^p -(x)^p (-x)^p -(x^p)" |
|||
PRINT "----------------+---------------------------------------------" |
|||
FOR x = -5 TO 5 STEP 10 |
|||
FOR p = 2 TO 3 |
|||
PRINT USING " ## ## | #### #### #### ####": x, p, (-x^p), (-(x)^p), ((-x)^p), (-(x^p)) |
|||
NEXT p |
|||
NEXT x |
|||
END</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as FreeBASIC entry.</pre> |
|||
==={{header|PureBasic}}=== |
|||
<syntaxhighlight lang="purebasic">OpenConsole() |
|||
PrintN(" x p | -x^p -(x)^p (-x)^p -(x^p)") |
|||
PrintN("----------------+---------------------------------------") |
|||
For x.i = -5 To 5 Step 10 |
|||
For p.i = 2 To 3 |
|||
PrintN(" " + Str(x) + " " + Str(p) + " | " + StrD(Pow(-x,p),0) + #TAB$ + StrD(Pow(-1*(x),p),0) + #TAB$ + StrD(Pow((-x),p),0) + #TAB$ + " " + StrD(-1*Pow(x,p),0)) |
|||
Next p |
|||
Next x |
|||
Input() |
|||
CloseConsole()</syntaxhighlight> |
|||
{{out}} |
|||
<pre> x p | -x^p -(x)^p (-x)^p -(x^p) |
|||
----------------+--------------------------------------- |
|||
-5 2 | 25 25 25 -25 |
|||
-5 3 | 125 125 125 125 |
|||
5 2 | 25 25 25 -25 |
|||
5 3 | -125 -125 -125 -125</pre> |
|||
==={{header|XBasic}}=== |
|||
{{works with|Windows XBasic}} |
|||
<syntaxhighlight lang="xbasic">PROGRAM "Exponentiation with infix operators in (or operating on) the base" |
|||
DECLARE FUNCTION Entry () |
|||
FUNCTION Entry () |
|||
PRINT " x p | -x**p -(x)**p (-x)**p -(x**p)" |
|||
PRINT "----------------+-----------------------------------------------" |
|||
FOR x = -5 TO 5 STEP 10 |
|||
FOR p = 2 TO 3 |
|||
PRINT " "; FORMAT$("##",x); " "; FORMAT$("##",p); " | "; FORMAT$("######",(-x**p)); " "; FORMAT$("######",(-(x)**p)); " "; FORMAT$("######",((-x)**p)); " "; FORMAT$("######",(-(x**p))) |
|||
NEXT p |
|||
NEXT x |
|||
END FUNCTION |
|||
END PROGRAM</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Similar to FreeBASIC entry.</pre> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic">print " x p | -x^p -(x)^p (-x)^p -(x^p)" |
|||
print "----------------+---------------------------------------------" |
|||
for x = -5 to 5 step 10 |
|||
for p = 2 to 3 |
|||
print " ", x using "##", " ", p using "##", " | ", (-x^p) using "####", " ", (-(x)^p) using "####", " ", ((-x)^p) using "####", " ", (-(x^p)) using "####" |
|||
next p |
|||
next x</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as FreeBASIC entry.</pre> |
|||
=={{header|EasyLang}}== |
|||
<syntaxhighlight> |
|||
for x in [ -5 5 ] |
|||
for p in [ 2 3 ] |
|||
print x & "^" & p & " = " & pow x p |
|||
. |
|||
. |
|||
</syntaxhighlight> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
F# does not support the ** operator for integers but for floats: |
F# does not support the ** operator for integers but for floats: |
||
< |
<syntaxhighlight lang="fsharp"> |
||
printfn "-5.0**2.0=%f; -(5.0**2.0)=%f" (-5.0**2.0) (-(5.0**2.0)) |
printfn "-5.0**2.0=%f; -(5.0**2.0)=%f" (-5.0**2.0) (-(5.0**2.0)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 97: | Line 341: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: infix locals prettyprint sequences |
||
sequences.generalizations sequences.repeating ; |
sequences.generalizations sequences.repeating ; |
||
Line 111: | Line 355: | ||
5 2 row |
5 2 row |
||
5 3 row |
5 3 row |
||
5 narray simple-table.</ |
5 narray simple-table.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 119: | Line 363: | ||
5 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 |
5 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 |
||
5 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125 |
5 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125 |
||
</pre> |
|||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight lang="freebasic">print " x p | -x^p -(x)^p (-x)^p -(x^p)" |
|||
print "----------------+---------------------------------------------" |
|||
for x as integer = -5 to 5 step 10 |
|||
for p as integer = 2 to 3 |
|||
print using " ## ## | #### #### #### ####";_ |
|||
x;p;(-x^p);(-(x)^p);((-x)^p);(-(x^p)) |
|||
next p |
|||
next x</syntaxhighlight> |
|||
{{out}}<pre> |
|||
x p | -x^p -(x)^p (-x)^p -(x^p) |
|||
----------------+--------------------------------------------- |
|||
-5 2 | -25 -25 25 -25 |
|||
-5 3 | 125 125 125 125 |
|||
5 2 | -25 -25 25 -25 |
|||
5 3 | -125 -125 -125 -125 |
|||
</pre> |
</pre> |
||
Line 129: | Line 391: | ||
Note that we can't call the method ''↑'' (or similar) because identifiers in Go must begin with a Unicode letter and using a non-ASCII symbol would be awkward to type on some keyboards in any case. |
Note that we can't call the method ''↑'' (or similar) because identifiers in Go must begin with a Unicode letter and using a non-ASCII symbol would be awkward to type on some keyboards in any case. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 151: | Line 413: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 159: | Line 421: | ||
x = 5 e = 2 | -x.p(e) = -25 | -(x).p(e) = -25 | (-x).p(e) = 25 | -(x.p(e)) = -25 |
x = 5 e = 2 | -x.p(e) = -25 | -(x).p(e) = -25 | (-x).p(e) = 25 | -(x.p(e)) = -25 |
||
x = 5 e = 3 | -x.p(e) = -125 | -(x).p(e) = -125 | (-x).p(e) = -125 | -(x.p(e)) = -125 |
x = 5 e = 3 | -x.p(e) = -125 | -(x).p(e) = -125 | (-x).p(e) = -125 | -(x.p(e)) = -125 |
||
</pre> |
|||
=={{header|Haskell}}== |
|||
<syntaxhighlight lang="haskell">--https://wiki.haskell.org/Power_function |
|||
main = do |
|||
print [-5^2,-(5)^2,(-5)^2,-(5^2)] --Integer |
|||
print [-5^^2,-(5)^^2,(-5)^^2,-(5^^2)] --Fractional |
|||
print [-5**2,-(5)**2,(-5)**2,-(5**2)] --Real |
|||
print [-5^3,-(5)^3,(-5)^3,-(5^3)] --Integer |
|||
print [-5^^3,-(5)^^3,(-5)^^3,-(5^^3)] --Fractional |
|||
print [-5**3,-(5)**3,(-5)**3,-(5**3)] --Real</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[-25,-25,25,-25] |
|||
[-25.0,-25.0,25.0,-25.0] |
|||
[-25.0,-25.0,25.0,-25.0] |
|||
[-125,-125,-125,-125] |
|||
[-125.0,-125.0,-125.0,-125.0] |
|||
[-125.0,-125.0,-125.0,-125.0]</pre> |
|||
=={{header|J}}== |
|||
APLs use a negative sign distinguished from minus as a different character. Underscore followed by a number specifies a negative number. APLs also process the operations from right to left, evaluating parenthesized expressions when the interpreter comes to them. In J, unary plus returns complex conjugate, which won't affect the outcome of this experiment. |
|||
<pre> |
|||
format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ]) |
|||
S=: 'x = {} p = {} -x^p {} -(x)^p {} (-x)^p {} -(x^p) {}' |
|||
explicit=: dyad def 'S format~ 2 2 4 4 4 4 ":&> x,y,(-x^y),(-(x)^y),((-x)^y),(-(x^y))' |
|||
tacit=: S format~ 2 2 4 4 4 4 ":&> [`]`([:-^)`([:-^)`((^~-)~)`([:-^)`:0 |
|||
_2 explicit/\_5 2 _5 3 5 2 5 3 |
|||
x = _5 p = 2 -x^p _25 -(x)^p _25 (-x)^p 25 -(x^p) _25 |
|||
x = _5 p = 3 -x^p 125 -(x)^p 125 (-x)^p 125 -(x^p) 125 |
|||
x = 5 p = 2 -x^p _25 -(x)^p _25 (-x)^p 25 -(x^p) _25 |
|||
x = 5 p = 3 -x^p _125 -(x)^p _125 (-x)^p _125 -(x^p) _125 |
|||
-:/ 1 0 2 |: _2(tacit ,: explicit)/\_5 2 _5 3 5 2 5 3 NB. the verbs produce matching results |
|||
1 |
|||
</pre> |
</pre> |
||
Line 164: | Line 461: | ||
In Julia, the ^ symbol is the power infix operator. The ^ operator has a higher precedence than the - operator, |
In Julia, the ^ symbol is the power infix operator. The ^ operator has a higher precedence than the - operator, |
||
so -5^2 is -25 and (-5)^2 is 25. |
so -5^2 is -25 and (-5)^2 is 25. |
||
< |
<syntaxhighlight lang="julia"> |
||
for x in [-5, 5], p in [2, 3] |
for x in [-5, 5], p in [2, 3] |
||
println("x is", lpad(x, 3), ", p is $p, -x^p is", lpad(-x^p, 4), ", -(x)^p is", |
println("x is", lpad(x, 3), ", p is $p, -x^p is", lpad(-x^p, 4), ", -(x)^p is", |
||
lpad(-(x)^p, 5), ", (-x)^p is", lpad((-x)^p, 5), ", -(x^p) is", lpad(-(x^p), 5)) |
lpad(-(x)^p, 5), ", (-x)^p is", lpad((-x)^p, 5), ", -(x^p) is", lpad(-(x^p), 5)) |
||
end |
end |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre> |
<pre> |
||
x is -5, p is 2, -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 |
x is -5, p is 2, -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 |
||
Line 176: | Line 473: | ||
x is 5, p is 3, -x^p is-125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125 |
x is 5, p is 3, -x^p is-125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125 |
||
</pre> |
</pre> |
||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur">writeln [-5^2, -(5)^2, (-5)^2, -(5^2)] |
|||
writeln [-5^3, -(5)^3, (-5)^3, -(5^3)] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[-25, -25, 25, -25] |
|||
[-125, -125, -125, -125] |
|||
</pre> |
|||
=={{header|Lua}}== |
|||
Lua < 5.3 has a single double-precision numeric type. Lua >= 5.3 adds an integer numeric type. "^" is supported as an infix exponentiation operator for both types. |
|||
<syntaxhighlight lang="lua">mathtype = math.type or type -- polyfill <5.3 |
|||
function test(xs, ps) |
|||
for _,x in ipairs(xs) do |
|||
for _,p in ipairs(ps) do |
|||
print(string.format("%2.f %7s %2.f %7s %4.f %4.f %4.f %4.f", x, mathtype(x), p, mathtype(p), -x^p, -(x)^p, (-x)^p, -(x^p))) |
|||
end |
|||
end |
|||
end |
|||
print(" x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p)") |
|||
print("-- ------- -- ------- ------ ------ ------ ------") |
|||
test( {-5.,5.}, {2.,3.} ) -- "float" (or "number" if <5.3) |
|||
if math.type then -- if >=5.3 |
|||
test( {-5,5}, {2,3} ) -- "integer" |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre> x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p) |
|||
-- ------- -- ------- ------ ------ ------ ------ |
|||
-5 float 2 float -25 -25 25 -25 |
|||
-5 float 3 float 125 125 125 125 |
|||
5 float 2 float -25 -25 25 -25 |
|||
5 float 3 float -125 -125 -125 -125 |
|||
-5 integer 2 integer -25 -25 25 -25 |
|||
-5 integer 3 integer 125 125 125 125 |
|||
5 integer 2 integer -25 -25 25 -25 |
|||
5 integer 3 integer -125 -125 -125 -125</pre> |
|||
=={{header|Maple}}== |
|||
<syntaxhighlight lang="maple">[-5**2,-(5)**2,(-5)**2,-(5**2)]; |
|||
[-25, -25, 25, -25] |
|||
[-5**3,-(5)**3,(-5)**3,-(5**3)]; |
|||
[-125, -125, -125, -125]</syntaxhighlight> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">{-5^2, -(5)^2, (-5)^2, -(5^2)} |
|||
{-5^3, -(5)^3, (-5)^3, -(5^3)}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>{-25, -25, 25, -25} |
|||
{-125, -125, -125, -125}</pre> |
|||
=={{header|Nim}}== |
|||
The infix exponentiation operator is defined in standard module “math”. Its precedence is less than that of unary “-” operator, so -5^2 is 25 and -(5^2) is -25. |
|||
<syntaxhighlight lang="nim">import math, strformat |
|||
for x in [-5, 5]: |
|||
for p in [2, 3]: |
|||
echo &"x is {x:2}, ", &"p is {p:1}, ", |
|||
&"-x^p is {-x^p:4}, ", &"-(x)^p is {-(x)^p:4}, ", |
|||
&"(-x)^p is {(-x)^p:4}, ", &"-(x^p) is {-(x^p):4}"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>x is -5, p is 2, -x^p is 25, -(x)^p is 25, (-x)^p is 25, -(x^p) is -25 |
|||
x is -5, p is 3, -x^p is 125, -(x)^p is 125, (-x)^p is 125, -(x^p) is 125 |
|||
x is 5, p is 2, -x^p is 25, -(x)^p is 25, (-x)^p is 25, -(x^p) is -25 |
|||
x is 5, p is 3, -x^p is -125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125</pre> |
|||
=={{header|Pascal}}== |
|||
{{works with|Extended Pascal}} |
|||
Apart from the built-in (prefix) functions <tt>sqr</tt> (exponent = 2) and <tt>sqrt</tt> (exponent = 0.5) already defined in Standard “Unextended” Pascal (ISO standard 7185), ''Extended Pascal'' (ISO standard 10206) defines following additional (infix) operators: |
|||
<syntaxhighlight lang="pascal">program exponentiationWithInfixOperatorsInTheBase(output); |
|||
const |
|||
minimumWidth = 7; |
|||
fractionDigits = minimumWidth div 4 + 1; |
|||
procedure testIntegerPower( |
|||
{ `pow` can in fact accept `integer`, `real` and `complex`. } |
|||
protected base: integer; |
|||
{ For `pow` the `exponent` _has_ to be an `integer`. } |
|||
protected exponent: integer |
|||
); |
|||
begin |
|||
writeLn('=====> testIntegerPower <====='); |
|||
writeLn(' base = ', base:minimumWidth); |
|||
writeLn(' exponent = ', exponent:minimumWidth); |
|||
{ Note: `exponent` may not be negative if `base` is zero! } |
|||
writeLn(' -base pow exponent = ', -base pow exponent:minimumWidth); |
|||
writeLn('-(base) pow exponent = ', -(base) pow exponent:minimumWidth); |
|||
writeLn('(-base) pow exponent = ', (-base) pow exponent:minimumWidth); |
|||
writeLn('-(base pow exponent) = ', -(base pow exponent):minimumWidth) |
|||
end; |
|||
procedure testRealPower( |
|||
{ `**` actually accepts all data types (`integer`, `real`, `complex`). } |
|||
protected base: real; |
|||
{ The `exponent` in an `**` expression will be, if applicable, } |
|||
{ _promoted_ to a `real` value approximation. } |
|||
protected exponent: integer |
|||
); |
|||
begin |
|||
writeLn('======> testRealPower <======'); |
|||
writeLn(' base = ', base:minimumWidth:fractionDigits); |
|||
writeLn(' exponent = ', exponent:pred(minimumWidth, succ(fractionDigits))); |
|||
if base > 0.0 then |
|||
begin |
|||
{ The result of `base ** exponent` is a `complex` value } |
|||
{ `base` is a `complex` value, `real` otherwise. } |
|||
writeLn(' -base ** exponent = ', -base ** exponent:minimumWidth:fractionDigits); |
|||
writeLn('-(base) ** exponent = ', -(base) ** exponent:minimumWidth:fractionDigits); |
|||
writeLn('(-base) ** exponent = illegal'); |
|||
writeLn('-(base ** exponent) = ', -(base ** exponent):minimumWidth:fractionDigits) |
|||
end |
|||
else |
|||
begin |
|||
{ “negative” zero will not alter the sign of the value. } |
|||
writeLn(' -base ** exponent = ', -base pow exponent:minimumWidth:fractionDigits); |
|||
writeLn('-(base) ** exponent = ', -(base) pow exponent:minimumWidth:fractionDigits); |
|||
writeLn('(-base) ** exponent = ', (-base) pow exponent:minimumWidth:fractionDigits); |
|||
writeLn('-(base ** exponent) = ', -(base pow exponent):minimumWidth:fractionDigits) |
|||
end |
|||
end; |
|||
{ === MAIN =================================================================== } |
|||
begin |
|||
testIntegerPower(-5, 2); |
|||
testIntegerPower(+5, 2); |
|||
testIntegerPower(-5, 3); |
|||
testIntegerPower( 5, 3); |
|||
testRealPower(-5.0, 2); |
|||
testRealPower(+5.0, 2); |
|||
testRealPower(-5E0, 3); |
|||
testRealPower(+5E0, 3) |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
=====> testIntegerPower <===== |
|||
base = -5 |
|||
exponent = 2 |
|||
-base pow exponent = -25 |
|||
-(base) pow exponent = -25 |
|||
(-base) pow exponent = 25 |
|||
-(base pow exponent) = -25 |
|||
=====> testIntegerPower <===== |
|||
base = 5 |
|||
exponent = 2 |
|||
-base pow exponent = -25 |
|||
-(base) pow exponent = -25 |
|||
(-base) pow exponent = 25 |
|||
-(base pow exponent) = -25 |
|||
=====> testIntegerPower <===== |
|||
base = -5 |
|||
exponent = 3 |
|||
-base pow exponent = 125 |
|||
-(base) pow exponent = 125 |
|||
(-base) pow exponent = 125 |
|||
-(base pow exponent) = 125 |
|||
=====> testIntegerPower <===== |
|||
base = 5 |
|||
exponent = 3 |
|||
-base pow exponent = -125 |
|||
-(base) pow exponent = -125 |
|||
(-base) pow exponent = -125 |
|||
-(base pow exponent) = -125 |
|||
======> testRealPower <====== |
|||
base = -5.00 |
|||
exponent = 2 |
|||
-base ** exponent = -25.00 |
|||
-(base) ** exponent = -25.00 |
|||
(-base) ** exponent = 25.00 |
|||
-(base ** exponent) = -25.00 |
|||
======> testRealPower <====== |
|||
base = 5.00 |
|||
exponent = 2 |
|||
-base ** exponent = -25.00 |
|||
-(base) ** exponent = -25.00 |
|||
(-base) ** exponent = illegal |
|||
-(base ** exponent) = -25.00 |
|||
======> testRealPower <====== |
|||
base = -5.00 |
|||
exponent = 3 |
|||
-base ** exponent = 125.00 |
|||
-(base) ** exponent = 125.00 |
|||
(-base) ** exponent = 125.00 |
|||
-(base ** exponent) = 125.00 |
|||
======> testRealPower <====== |
|||
base = 5.00 |
|||
exponent = 3 |
|||
-base ** exponent = -125.00 |
|||
-(base) ** exponent = -125.00 |
|||
(-base) ** exponent = illegal |
|||
-(base ** exponent) = -125.00 |
|||
Since there are ''two'' different power operators available, both accepting operands of different data types, having different limits, and yielding different data types, it was not sensible to produce a table similar to other entries on this page. |
|||
=={{header|Perl}}== |
|||
Use the module <tt>Sub::Infix</tt> to define a custom operator. Note that the bracketing punctuation controls the precedence level. Results structured same as in Raku example. |
|||
<syntaxhighlight lang="perl">use strict; |
|||
use warnings; |
|||
use Sub::Infix; |
|||
BEGIN { *e = infix { $_[0] ** $_[1] } }; # operator needs to be defined at compile time |
|||
my @eqns = ('1 + -$xOP$p', '1 + (-$x)OP$p', '1 + (-($x)OP$p)', '(1 + -$x)OP$p', '1 + -($xOP$p)'); |
|||
for my $op ('**', '/e/', '|e|') { |
|||
for ( [-5, 2], [-5, 3], [5, 2], [5, 3] ) { |
|||
my( $x, $p, $eqn ) = @$_; |
|||
printf 'x: %2d p: %2d |', $x, $p; |
|||
$eqn = s/OP/$op/gr and printf '%17s %4d |', $eqn, eval $eqn for @eqns; |
|||
print "\n"; |
|||
} |
|||
print "\n"; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>x: -5 p: 2 | 1 + -$x**$p -24 | 1 + (-$x)**$p 26 | 1 + (-($x)**$p) -24 | (1 + -$x)**$p 36 | 1 + -($x**$p) -24 | |
|||
x: -5 p: 3 | 1 + -$x**$p 126 | 1 + (-$x)**$p 126 | 1 + (-($x)**$p) 126 | (1 + -$x)**$p 216 | 1 + -($x**$p) 126 | |
|||
x: 5 p: 2 | 1 + -$x**$p -24 | 1 + (-$x)**$p 26 | 1 + (-($x)**$p) -24 | (1 + -$x)**$p 16 | 1 + -($x**$p) -24 | |
|||
x: 5 p: 3 | 1 + -$x**$p -124 | 1 + (-$x)**$p -124 | 1 + (-($x)**$p) -124 | (1 + -$x)**$p -64 | 1 + -($x**$p) -124 | |
|||
x: -5 p: 2 | 1 + -$x/e/$p 26 | 1 + (-$x)/e/$p 26 | 1 + (-($x)/e/$p) 26 | (1 + -$x)/e/$p 36 | 1 + -($x/e/$p) -24 | |
|||
x: -5 p: 3 | 1 + -$x/e/$p 126 | 1 + (-$x)/e/$p 126 | 1 + (-($x)/e/$p) 126 | (1 + -$x)/e/$p 216 | 1 + -($x/e/$p) 126 | |
|||
x: 5 p: 2 | 1 + -$x/e/$p 26 | 1 + (-$x)/e/$p 26 | 1 + (-($x)/e/$p) 26 | (1 + -$x)/e/$p 16 | 1 + -($x/e/$p) -24 | |
|||
x: 5 p: 3 | 1 + -$x/e/$p -124 | 1 + (-$x)/e/$p -124 | 1 + (-($x)/e/$p) -124 | (1 + -$x)/e/$p -64 | 1 + -($x/e/$p) -124 | |
|||
x: -5 p: 2 | 1 + -$x|e|$p 36 | 1 + (-$x)|e|$p 36 | 1 + (-($x)|e|$p) 26 | (1 + -$x)|e|$p 36 | 1 + -($x|e|$p) -24 | |
|||
x: -5 p: 3 | 1 + -$x|e|$p 216 | 1 + (-$x)|e|$p 216 | 1 + (-($x)|e|$p) 126 | (1 + -$x)|e|$p 216 | 1 + -($x|e|$p) 126 | |
|||
x: 5 p: 2 | 1 + -$x|e|$p 16 | 1 + (-$x)|e|$p 16 | 1 + (-($x)|e|$p) 26 | (1 + -$x)|e|$p 16 | 1 + -($x|e|$p) -24 | |
|||
x: 5 p: 3 | 1 + -$x|e|$p -64 | 1 + (-$x)|e|$p -64 | 1 + (-($x)|e|$p) -124 | (1 + -$x)|e|$p -64 | 1 + -($x|e|$p) -124 |</pre> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
Phix has a power() function instead of an infix operator, hence there are only two possible syntaxes, with the obvious outcomes.<br> |
Phix has a power() function instead of an infix operator, hence there are only two possible syntaxes, with the obvious outcomes.<br> |
||
(Like Go, Phix does not support operator overloading or definition at all.) |
(Like Go, Phix does not support operator overloading or definition at all.) |
||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<lang Phix>for x=-5 to 5 by 10 do |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">x<span style="color: #0000FF;">=<span style="color: #0000FF;">-<span style="color: #000000;">5</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">by</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> |
|||
for p=2 to 3 do |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">p<span style="color: #0000FF;">=<span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span> |
|||
printf(1,"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n",{x,p,power(-x,p),-power(x,p)}) |
|||
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">x<span style="color: #0000FF;">,<span style="color: #000000;">p<span style="color: #0000FF;">,<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #0000FF;">-<span style="color: #000000;">x<span style="color: #0000FF;">,<span style="color: #000000;">p<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #0000FF;">-<span style="color: #7060A8;">power<span style="color: #0000FF;">(<span style="color: #000000;">x<span style="color: #0000FF;">,<span style="color: #000000;">p<span style="color: #0000FF;">)<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span> |
|||
end for |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
end for</lang> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 192: | Line 724: | ||
x = 5, p = 3, power(-x,p) = -125, -power(x,p) = -125 |
x = 5, p = 3, power(-x,p) = -125, -power(x,p) = -125 |
||
</pre> |
</pre> |
||
=={{header|QB64}}== |
|||
<syntaxhighlight lang="qb64">For x = -5 To 5 Step 10 |
|||
For p = 2 To 3 |
|||
Print "x = "; x; " p ="; p; " "; |
|||
Print Using "-x^p is ####"; -x ^ p; |
|||
Print Using ", -(x)^p is ####"; -(x) ^ p; |
|||
Print Using ", (-x)^p is ####"; (-x) ^ p; |
|||
Print Using ", -(x^p) is ####"; -(x ^ p) |
|||
Next |
|||
Next</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
x = -5 p = 2 -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 |
|||
x = -5 p = 3 -x^p is 125, -(x)^p is 125, (-x)^p is 125, -(x^p) is 125 |
|||
x = 5 p = 2 -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 |
|||
x = 5 p = 3 -x^p is -125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125 |
|||
</pre> |
|||
=={{header|R}}== |
|||
<syntaxhighlight lang="rsplus">expressions <- alist(-x ^ p, -(x) ^ p, (-x) ^ p, -(x ^ p)) |
|||
x <- c(-5, -5, 5, 5) |
|||
p <- c(2, 3, 2, 3) |
|||
output <- data.frame(x, |
|||
p, |
|||
setNames(lapply(expressions, eval), sapply(expressions, deparse)), |
|||
check.names = FALSE) |
|||
print(output, row.names = FALSE)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> x p -x^p -(x)^p (-x)^p -(x^p) |
|||
-5 2 -25 -25 25 -25 |
|||
-5 3 125 125 125 125 |
|||
5 2 -25 -25 25 -25 |
|||
5 3 -125 -125 -125 -125</pre> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 203: | Line 768: | ||
Also add a different grouping: <code>(1 + -x){exponential operator}p</code> |
Also add a different grouping: <code>(1 + -x){exponential operator}p</code> |
||
<lang |
<syntaxhighlight lang="raku" line>sub infix:<↑> is looser(&prefix:<->) { $^a ** $^b } |
||
sub infix:< |
sub infix:<∧> is looser(&infix:<->) { $^a ** $^b } |
||
for |
|||
use MONKEY; |
|||
('Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.', |
|||
'1 + -$x**$p', {1 + -$^a**$^b}, '1 + (-$x)**$p', {1 + (-$^a)**$^b}, '1 + (-($x)**$p)', {1 + (-($^a)**$^b)}, |
|||
'(1 + -$x)**$p', {(1 + -$^a)**$^b}, '1 + -($x**$p)', {1 + -($^a**$^b)}), |
|||
("\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.", |
|||
'1 + -$x↑$p ', {1 + -$^a↑$^b}, '1 + (-$x)↑$p ', {1 + (-$^a)↑$^b}, '1 + (-($x)↑$p) ', {1 + (-($^a)↑$^b)}, |
|||
'(1 + -$x)↑$p ', {(1 + -$^a)↑$^b}, '1 + -($x↑$p) ', {1 + -($^a↑$^b)}), |
|||
("\nEven more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.", |
|||
'1 + -$x∧$p ', {1 + -$^a∧$^b}, '1 + (-$x)∧$p ', {1 + (-$^a)∧$^b}, '1 + (-($x)∧$p) ', {1 + (-($^a)∧$^b)}, |
|||
'(1 + -$x)∧$p ', {(1 + -$^a)∧$^b}, '1 + -($x∧$p) ', {1 + -($^a∧$^b)}) |
|||
-> $case { |
|||
"\nEven moreso: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.", |
|||
my ($title, @operations) = $case<>; |
|||
('1 + -$x^$p ', '1 + (-$x)^$p ', '1 + (-($x)^$p) ', '(1 + -$x)^$p ', '1 + -($x^$p) ') |
|||
say $title; |
|||
say $message; |
|||
for -5, 5 X 2, 3 -> ($x, $p) { |
for -5, 5 X 2, 3 -> ($x, $p) { |
||
printf "x = %2d p = %d", $x, $p; |
printf "x = %2d p = %d", $x, $p; |
||
-> $ |
for @operations -> $label, &code { print " │ $label = " ~ $x.&code($p).fmt('%4d') } |
||
say '' |
|||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Default precedence: infix exponentiation is tighter (higher) precedence than unary negation. |
<pre>Default precedence: infix exponentiation is tighter (higher) precedence than unary negation. |
||
Line 237: | Line 805: | ||
x = 5 p = 3 │ 1 + -$x↑$p = -124 │ 1 + (-$x)↑$p = -124 │ 1 + (-($x)↑$p) = -124 │ (1 + -$x)↑$p = -64 │ 1 + -($x↑$p) = -124 |
x = 5 p = 3 │ 1 + -$x↑$p = -124 │ 1 + (-$x)↑$p = -124 │ 1 + (-($x)↑$p) = -124 │ (1 + -$x)↑$p = -64 │ 1 + -($x↑$p) = -124 |
||
Even |
Even more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction. |
||
x = -5 p = 2 │ 1 + -$ |
x = -5 p = 2 │ 1 + -$x∧$p = 36 │ 1 + (-$x)∧$p = 36 │ 1 + (-($x)∧$p) = 26 │ (1 + -$x)∧$p = 36 │ 1 + -($x∧$p) = -24 |
||
x = -5 p = 3 │ 1 + -$ |
x = -5 p = 3 │ 1 + -$x∧$p = 216 │ 1 + (-$x)∧$p = 216 │ 1 + (-($x)∧$p) = 126 │ (1 + -$x)∧$p = 216 │ 1 + -($x∧$p) = 126 |
||
x = 5 p = 2 │ 1 + -$ |
x = 5 p = 2 │ 1 + -$x∧$p = 16 │ 1 + (-$x)∧$p = 16 │ 1 + (-($x)∧$p) = 26 │ (1 + -$x)∧$p = 16 │ 1 + -($x∧$p) = -24 |
||
x = 5 p = 3 │ 1 + -$ |
x = 5 p = 3 │ 1 + -$x∧$p = -64 │ 1 + (-$x)∧$p = -64 │ 1 + (-($x)∧$p) = -124 │ (1 + -$x)∧$p = -64 │ 1 + -($x∧$p) = -124</pre> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program shows exponentition with an infix operator (implied and/or specified).*/ |
||
_= '─'; ! = '║'; mJunct= '─╫─'; bJunct= '─╨─' /*define some special glyphs. */ |
_= '─'; ! = '║'; mJunct= '─╫─'; bJunct= '─╨─' /*define some special glyphs. */ |
||
Line 267: | Line 835: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
@: parse arg txt, w, fill; if fill=='' then fill= ' '; return center( txt, w, fill) |
@: parse arg txt, w, fill; if fill=='' then fill= ' '; return center( txt, w, fill) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out|output|text= when using the internal default input:}} |
{{out|output|text= when using the internal default input:}} |
||
<pre> |
<pre> |
||
Line 278: | Line 846: | ||
5 3 ║ -x**p -125 ║ -(x)**p -125 ║ (-x)**p -125 ║ -(x**p) -125 |
5 3 ║ -x**p -125 ║ -(x)**p -125 ║ (-x)**p -125 ║ -(x**p) -125 |
||
───── ──────╨─────────── ───────╨─────────── ───────╨─────────── ───────╨─────────── ────── |
───── ──────╨─────────── ───────╨─────────── ───────╨─────────── ───────╨─────────── ────── |
||
</pre> |
|||
=={{header|RPL}}== |
|||
Using infix exponentiation as required, even if not RPLish: |
|||
≪ → x p |
|||
≪ '''{ 'x' 'p' '-x^p' '-(x)^p' '(-x)^p' '-(x^p)' }''' 1 |
|||
DO GETI EVAL ROT ROT UNTIL DUP 1 == END |
|||
DROP 7 ROLLD 6 →LIST |
|||
≫ ≫ 'SHOXP' STO |
|||
{{in}} |
|||
<pre> |
|||
-5 2 SHOXP |
|||
-5 3 SHOXP |
|||
5 2 SHOXP |
|||
5 3 SHOXP |
|||
</pre> |
|||
{{out}} |
|||
<pre> |
|||
8: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } |
|||
7: { -5 2 -25 -25 25 -25 } |
|||
6: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } |
|||
5: { -5 3 125 125 125 125 } |
|||
4: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } |
|||
3: { 5 2 -25 -25 25 -25 } |
|||
2: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } |
|||
1: { 5 3 -125 -125 -125 -125 } |
|||
</pre> |
|||
Original infix expressions (see code above in bold characters) have been simplified by the interpreter when storing the program. |
|||
In reverse Polish notation, there is only one way to answer the task: |
|||
≪ → x p |
|||
≪ x NEG p ^ |
|||
≫ ≫ 'SHOXP' STO |
|||
=={{header|Ruby}}== |
|||
<syntaxhighlight lang="ruby">nums = [-5, 5] |
|||
pows = [2, 3] |
|||
nums.product(pows) do |x, p| |
|||
puts "x = #{x} p = #{p}\t-x**p #{-x**p}\t-(x)**p #{-(x)**p}\t(-x)**p #{ (-x)**p}\t-(x**p) #{-(x**p)}" |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>x = -5 p = 2 -x**p -25 -(x)**p -25 (-x)**p 25 -(x**p) -25 |
|||
x = -5 p = 3 -x**p 125 -(x)**p 125 (-x)**p 125 -(x**p) 125 |
|||
x = 5 p = 2 -x**p -25 -(x)**p -25 (-x)**p 25 -(x**p) -25 |
|||
x = 5 p = 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125 |
|||
</pre> |
</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">from itertools import product |
||
xx = '-5 +5'.split() |
xx = '-5 +5'.split() |
||
Line 299: | Line 911: | ||
for x, p in product(xx, pp): |
for x, p in product(xx, pp): |
||
texts2 = [t.replace(X, x).replace(P, p) for t in texts] |
texts2 = [t.replace(X, x).replace(P, p) for t in texts] |
||
print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))</ |
print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 316: | Line 928: | ||
+5**3 == 125; -+5**3 ==-125; -(+5)**3 ==-125; (-+5)**3 ==-125; -(+5**3) ==-125</pre> |
+5**3 == 125; -+5**3 ==-125; -(+5)**3 ==-125; (-+5)**3 ==-125; -(+5**3) ==-125</pre> |
||
=={{header|Smalltalk}}== |
|||
Smalltalk has no prefix operator for negation. To negate, you have to send the number a "negated" message, which has higher precedence than any binary message. Literal constants may have a sign (which is not an operation, but part of the constant). |
|||
<syntaxhighlight lang="smalltalk">a := 2. |
|||
b := 3. |
|||
Transcript show:'-5**2 => '; showCR: -5**2. |
|||
Transcript show:'-5**a => '; showCR: -5**a. |
|||
Transcript show:'-5**b => '; showCR: -5**b. |
|||
Transcript show:'5**2 => '; showCR: 5**2. |
|||
Transcript show:'5**a => '; showCR: 5**a. |
|||
Transcript show:'5**b => '; showCR: 5**b. |
|||
" Transcript show:'-(5**b) => '; showCR: -(5**b). -- invalid: syntax error " |
|||
" Transcript show:'5**-b => '; showCR: 5**-b. -- invalid: syntax error "</syntaxhighlight> |
|||
Using the "negated" message: |
|||
<syntaxhighlight lang="smalltalk">Transcript show:'5 negated**2 => '; showCR: 5 negated**2. "negates 5" |
|||
Transcript show:'5 negated**3 => '; showCR: 5 negated**3. |
|||
Transcript show:'5**2 negated => '; showCR: 5**2 negated. "negates 2" |
|||
Transcript show:'5**3 negated => '; showCR: 5**3 negated. "negates 3" |
|||
Transcript show:'5 negated**a => '; showCR: 5 negated**a. |
|||
Transcript show:'5 negated**b => '; showCR: 5 negated**b. |
|||
Transcript show:'5**a negated => '; showCR: 5**a negated. |
|||
Transcript show:'5**b negated => '; showCR: 5**b negated. |
|||
Transcript show:'(5**a) negated => '; showCR: (5**a) negated. |
|||
Transcript show:'(5**b) negated => '; showCR: (5**b) negated. |
|||
Transcript show:'(-5**a) negated => '; showCR: (-5**a) negated. |
|||
Transcript show:'(-5**b) negated => '; showCR: (-5**b) negated. |
|||
Transcript show:'-5 negated**2 => '; showCR: -5 negated**2. "negates the negative 5" |
|||
Transcript show:'-5 negated**3 => '; showCR: -5 negated**3.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
-5**2 => 25 |
|||
-5**a => 25 |
|||
-5**b => -125 |
|||
5**2 => 25 |
|||
5**a => 25 |
|||
5**b => 125 |
|||
5 negated**2 => 25 |
|||
5 negated**3 => -125 |
|||
5**2 negated => (1/25) |
|||
5**3 negated => (1/125) |
|||
5 negated**a => 25 |
|||
5 negated**b => -125 |
|||
5**a negated => (1/25) |
|||
5**b negated => (1/125) |
|||
(5**a) negated => -25 |
|||
(5**b) negated => -125 |
|||
(-5**a) negated => -25 |
|||
(-5**b) negated => 125 |
|||
-5 negated**2 => 25 |
|||
-5 negated**3 => 125 |
|||
</pre> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
Wren uses the pow() method for exponentiation of numbers and, whilst it supports operator overloading, there is no way of adding a suitable infix operator to the existing Num class. |
Wren uses the pow() method for exponentiation of numbers and, whilst it supports operator overloading, there is no way of adding a suitable infix operator to the existing Num class or inheriting from that class. |
||
Also inheriting from the Num class is not recommended and will probably be banned altogether from the next version. |
|||
However, what we can do is to wrap Num objects in a new Num2 class and then add exponentiation and unary minus operators to that. |
However, what we can do is to wrap Num objects in a new Num2 class and then add exponentiation and unary minus operators to that. |
||
Ideally what we'd like to do is to use a new operator such as '**' for exponentiation (because '^' is the bitwise exclusive or operator) but we can only overload existing operators with their existing precedence and so, for the purposes of this task, '^' is the only realistic choice. |
Ideally what we'd like to do is to use a new operator such as '**' for exponentiation (because '^' is the bitwise exclusive or operator) but we can only overload existing operators with their existing precedence and so, for the purposes of this task, '^' is the only realistic choice. |
||
< |
<syntaxhighlight lang="wren">import "./fmt" for Fmt |
||
class Num2 { |
class Num2 { |
||
Line 352: | Line 1,013: | ||
Fmt.print("$s = $4s", ops[3], -(x^p)) |
Fmt.print("$s = $4s", ops[3], -(x^p)) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
Latest revision as of 19:04, 4 March 2024
You are encouraged to solve this task according to the task description, using any language you may know.
(Many programming languages, especially those with extended─precision integer arithmetic, usually
support one of **
, ^
, ↑
or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the POW or some other BIF
(Built─In Ffunction), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an infix operator operating
in (or operating on) the base.
- Example
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
- Task
-
- compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
- Raise the following numbers (integer or real):
- -5 and
- +5
- to the following powers:
- 2nd and
- 3rd
- using the following expressions (if applicable in your language):
- -x**p
- -(x)**p
- (-x)**p
- -(x**p)
- Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
- Related tasks
- Exponentiation order
- Exponentiation operator
- Arbitrary-precision integers (included)
- Parsing/RPN to infix conversion
- Operator precedence
- References
Ada
The order of precedence for Ada operators is:
logical_operator ::= and | or | xor relational_operator ::= = | /= | < | <= | > | >= binary_adding_operator ::= + | – | & unary_adding_operator ::= + | – multiplying_operator ::= * | / | mod | rem highest_precedence_operator ::= ** | abs | not
Ada provides an exponentiation operator for integer types and floating point types.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
ivalue : Integer := -5;
fvalue : float := -5.0;
begin
Put_Line("Integer exponentiation:");
for i in 1..2 loop
for power in 2..3 loop
Put("x =" & ivalue'image & " p =" & power'image);
Put(" -x ** p ");
Put(item => -ivalue ** power, width => 4);
Put(" -(x) ** p ");
Put(item => -(ivalue) ** power, width => 4);
Put(" (-x) ** p ");
Put(Item => (- ivalue) ** power, Width => 4);
Put(" -(x ** p) ");
Put(Item => -(ivalue ** power), Width => 4);
New_line;
end loop;
ivalue := 5;
fvalue := 5.0;
end loop;
Put_Line("floating point exponentiation:");
ivalue := -5;
fvalue := -5.0;
for i in 1..2 loop
for power in 2..3 loop
Put("x =" & fvalue'image & " p =" & power'image);
Put(" -x ** p ");
Put(item => -fvalue ** power, fore => 4, Aft => 1, Exp => 0);
Put(" -(x) ** p ");
Put(item => -(fvalue) ** power, fore => 4, Aft => 1, Exp => 0);
Put(" (-x) ** p ");
Put(Item => (- fvalue) ** power, fore => 4, Aft => 1, Exp => 0);
Put(" -(x ** p) ");
Put(Item => -(fvalue ** power), fore => 4, Aft => 1, Exp => 0);
New_line;
end loop;
ivalue := 5;
fvalue := 5.0;
end loop;
end Main;
- Output:
Integer exponentiation: x =-5 p = 2 -x ** p -25 -(x) ** p -25 (-x) ** p 25 -(x ** p) -25 x =-5 p = 3 -x ** p 125 -(x) ** p 125 (-x) ** p 125 -(x ** p) 125 x = 5 p = 2 -x ** p -25 -(x) ** p -25 (-x) ** p 25 -(x ** p) -25 x = 5 p = 3 -x ** p -125 -(x) ** p -125 (-x) ** p -125 -(x ** p) -125 floating point exponentiation: x =-5.00000E+00 p = 2 -x ** p -25.0 -(x) ** p -25.0 (-x) ** p 25.0 -(x ** p) -25.0 x =-5.00000E+00 p = 3 -x ** p 125.0 -(x) ** p 125.0 (-x) ** p 125.0 -(x ** p) 125.0 x = 5.00000E+00 p = 2 -x ** p -25.0 -(x) ** p -25.0 (-x) ** p 25.0 -(x ** p) -25.0 x = 5.00000E+00 p = 3 -x ** p -125.0 -(x) ** p -125.0 (-x) ** p -125.0 -(x ** p) -125.0
ALGOL 68
In Algol 68, all unary operators have a higher precedence than any binary operator.
Algol 68 also allows UP and ^ for the exponentiation operator.
BEGIN
# show the results of exponentiation and unary minus in various combinations #
FOR x FROM -5 BY 10 TO 5 DO
FOR p FROM 2 TO 3 DO
print( ( "x = ", whole( x, -2 ), " p = ", whole( p, 0 ) ) );
print( ( " -x**p ", whole( -x**p, -4 ) ) );
print( ( " -(x)**p ", whole( -(x)**p, -4 ) ) );
print( ( " (-x)**p ", whole( (-x)**p, -4 ) ) );
print( ( " -(x**p) ", whole( -(x**p), -4 ) ) );
print( ( newline ) )
OD
OD
END
- Output:
x = -5 p = 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 x = -5 p = 3 -x**p 125 -(x)**p 125 (-x)**p 125 -(x**p) 125 x = 5 p = 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 x = 5 p = 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125
AWK
# syntax: GAWK -f EXPONENTIATION_WITH_INFIX_OPERATORS_IN_OR_OPERATING_ON_THE_BASE.AWK
# converted from FreeBASIC
BEGIN {
print(" x p | -x^p -(x)^p (-x)^p -(x^p)")
print("--------+------------------------------------")
for (x=-5; x<=5; x+=10) {
for (p=2; p<=3; p++) {
printf("%3d %3d | %8d %8d %8d %8d\n",x,p,(-x^p),(-(x)^p),((-x)^p),(-(x^p)))
}
}
exit(0)
}
- Output:
x p | -x^p -(x)^p (-x)^p -(x^p) --------+------------------------------------ -5 2 | -25 -25 25 -25 -5 3 | 125 125 125 125 5 2 | -25 -25 25 -25 5 3 | -125 -125 -125 -125
BASIC
Applesoft BASIC
S$=" ":M$=CHR$(13):?M$" X P -X^P -(X)^P (-X)^P -(X^P)":FORX=-5TO+5STEP10:FORP=2TO3:?M$MID$("+",1+(X<0));X" "PRIGHT$(S$+STR$(-X^P),8)RIGHT$(S$+STR$(-(X)^P),8)RIGHT$(S$+STR$((-X)^P),8)RIGHT$(S$+STR$(-(X^P)),8);:NEXTP,X
- Output:
X P -X^P -(X)^P (-X)^P -(X^P) -5 2 25 25 25 -25 -5 3 125 125 125 125 +5 2 25 25 25 -25 +5 3 -125 -125 -125 -125
BASIC256
print " x p | -x^p -(x)^p (-x)^p -(x^p)"
print ("-"*15); "+"; ("-"*45)
for x = -5 to 5 step 10
for p = 2 to 3
print " "; rjust(x,2); " "; ljust(p,2); " | "; rjust((-x^p),6); " "; rjust((-(x)^p),6); (" "*6); rjust(((-x)^p),6); " "; rjust((-(x^p)),6)
next p
next x
- Output:
x p | -x^p -(x)^p (-x)^p -(x^p) ---------------+--------------------------------------------- -5 2 | -25.0 -25.0 25.0 -25.0 -5 3 | 125.0 125.0 125.0 125.0 5 2 | -25.0 -25.0 25.0 -25.0 5 3 | -125.0 -125.0 -125.0 -125.0
Gambas
Public Sub Main()
Print " x p | -x^p -(x)^p (-x)^p -(x^p)"
Print "----------------+---------------------------------------------"
For x As Integer = -5 To 5 Step 10
For p As Integer = 2 To 3
Print " "; Format$(x, "-#"); " "; Format$(p, "-#"); " | "; Format$((-x ^ p), "-###"); " "; Format$((-(x) ^ p), "-###"); " "; Format$(((-x) ^ p), "-###"); " "; Format$((-(x ^ p)), "-###")
Next
Next
End
- Output:
Same as FreeBASIC entry.
QBasic
PRINT " x p | -x^p -(x)^p (-x)^p -(x^p)"
PRINT "----------------+---------------------------------------------"
FOR x = -5 TO 5 STEP 10
FOR p = 2 TO 3
PRINT USING " ## ## | #### #### #### ####"; x; p; (-x ^ p); (-(x) ^ p); ((-x) ^ p); (-(x ^ p))
NEXT p
NEXT x
- Output:
Same as FreeBASIC entry.
Run BASIC
print " x"; chr$(9); " p"; chr$(9); " | "; chr$(9); "-x^p"; chr$(9); " "; chr$(9); "-(x)^p"; chr$(9); " "; chr$(9); "(-x)^p"; chr$(9); " "; chr$(9); "-(x^p)"
print "----------------------------+-----------------------------------------------------------------"
for x = -5 to 5 step 10
for p = 2 to 3
print " "; x; chr$(9); " "; chr$(9); p; chr$(9); " | "; chr$(9); (-1*x^p); chr$(9); " "; chr$(9); (-1*(x)^p); chr$(9); " "; chr$(9); ((-1*x)^p); chr$(9); " "; chr$(9); (-1*(x^p))
next p
next x
end
- Output:
Similar to FreeBASIC entry.
True BASIC
PRINT " x p | -x^p -(x)^p (-x)^p -(x^p)"
PRINT "----------------+---------------------------------------------"
FOR x = -5 TO 5 STEP 10
FOR p = 2 TO 3
PRINT USING " ## ## | #### #### #### ####": x, p, (-x^p), (-(x)^p), ((-x)^p), (-(x^p))
NEXT p
NEXT x
END
- Output:
Same as FreeBASIC entry.
PureBasic
OpenConsole()
PrintN(" x p | -x^p -(x)^p (-x)^p -(x^p)")
PrintN("----------------+---------------------------------------")
For x.i = -5 To 5 Step 10
For p.i = 2 To 3
PrintN(" " + Str(x) + " " + Str(p) + " | " + StrD(Pow(-x,p),0) + #TAB$ + StrD(Pow(-1*(x),p),0) + #TAB$ + StrD(Pow((-x),p),0) + #TAB$ + " " + StrD(-1*Pow(x,p),0))
Next p
Next x
Input()
CloseConsole()
- Output:
x p | -x^p -(x)^p (-x)^p -(x^p) ----------------+--------------------------------------- -5 2 | 25 25 25 -25 -5 3 | 125 125 125 125 5 2 | 25 25 25 -25 5 3 | -125 -125 -125 -125
XBasic
PROGRAM "Exponentiation with infix operators in (or operating on) the base"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
PRINT " x p | -x**p -(x)**p (-x)**p -(x**p)"
PRINT "----------------+-----------------------------------------------"
FOR x = -5 TO 5 STEP 10
FOR p = 2 TO 3
PRINT " "; FORMAT$("##",x); " "; FORMAT$("##",p); " | "; FORMAT$("######",(-x**p)); " "; FORMAT$("######",(-(x)**p)); " "; FORMAT$("######",((-x)**p)); " "; FORMAT$("######",(-(x**p)))
NEXT p
NEXT x
END FUNCTION
END PROGRAM
- Output:
Similar to FreeBASIC entry.
Yabasic
print " x p | -x^p -(x)^p (-x)^p -(x^p)"
print "----------------+---------------------------------------------"
for x = -5 to 5 step 10
for p = 2 to 3
print " ", x using "##", " ", p using "##", " | ", (-x^p) using "####", " ", (-(x)^p) using "####", " ", ((-x)^p) using "####", " ", (-(x^p)) using "####"
next p
next x
- Output:
Same as FreeBASIC entry.
EasyLang
for x in [ -5 5 ]
for p in [ 2 3 ]
print x & "^" & p & " = " & pow x p
.
.
F#
F# does not support the ** operator for integers but for floats:
printfn "-5.0**2.0=%f; -(5.0**2.0)=%f" (-5.0**2.0) (-(5.0**2.0))
- Output:
-5.0**2.0=25.000000; -(5.0**2.0)=-25.000000
Factor
USING: infix locals prettyprint sequences
sequences.generalizations sequences.repeating ;
:: row ( x p -- seq )
x p "-x**p" [infix -x**p infix]
"-(x)**p" [infix -(x)**p infix]
"(-x)**p" [infix (-x)**p infix]
"-(x**p)" [infix -(x**p) infix] 10 narray ;
{ "x value" "p value" } { "expression" "result" } 8 cycle append
-5 2 row
-5 3 row
5 2 row
5 3 row
5 narray simple-table.
- Output:
x value p value expression result expression result expression result expression result -5 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 -5 3 -x**p 125 -(x)**p 125 (-x)**p 125 -(x**p) 125 5 2 -x**p 25 -(x)**p 25 (-x)**p 25 -(x**p) -25 5 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125
FreeBASIC
print " x p | -x^p -(x)^p (-x)^p -(x^p)"
print "----------------+---------------------------------------------"
for x as integer = -5 to 5 step 10
for p as integer = 2 to 3
print using " ## ## | #### #### #### ####";_
x;p;(-x^p);(-(x)^p);((-x)^p);(-(x^p))
next p
next x
- Output:
x p | -x^p -(x)^p (-x)^p -(x^p)----------------+---------------------------------------------
-5 2 | -25 -25 25 -25 -5 3 | 125 125 125 125 5 2 | -25 -25 25 -25 5 3 | -125 -125 -125 -125
Go
Go uses the math.Pow function for exponentiation and doesn't support operator overloading at all. Consequently, it is not possible to conjure up an infix operator to do the same job.
Perhaps the closest we can get is to define a derived type (float say) based on float64 and then give it a method with a short name (p say) to provide exponentiation.
This looks odd but is perfectly workable as the following example shows. However, as a method call, x.p is always going to take precedence over the unary minus operator and will always require the exponent to be enclosed in parentheses.
Note that we can't call the method ↑ (or similar) because identifiers in Go must begin with a Unicode letter and using a non-ASCII symbol would be awkward to type on some keyboards in any case.
package main
import (
"fmt"
"math"
)
type float float64
func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }
func main() {
ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"}
for _, x := range []float{float(-5), float(5)} {
for _, e := range []float{float(2), float(3)} {
fmt.Printf("x = %2.0f e = %0.0f | ", x, e)
fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e))
fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e))
fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e))
fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e)))
}
}
}
- Output:
x = -5 e = 2 | -x.p(e) = -25 | -(x).p(e) = -25 | (-x).p(e) = 25 | -(x.p(e)) = -25 x = -5 e = 3 | -x.p(e) = 125 | -(x).p(e) = 125 | (-x).p(e) = 125 | -(x.p(e)) = 125 x = 5 e = 2 | -x.p(e) = -25 | -(x).p(e) = -25 | (-x).p(e) = 25 | -(x.p(e)) = -25 x = 5 e = 3 | -x.p(e) = -125 | -(x).p(e) = -125 | (-x).p(e) = -125 | -(x.p(e)) = -125
Haskell
--https://wiki.haskell.org/Power_function
main = do
print [-5^2,-(5)^2,(-5)^2,-(5^2)] --Integer
print [-5^^2,-(5)^^2,(-5)^^2,-(5^^2)] --Fractional
print [-5**2,-(5)**2,(-5)**2,-(5**2)] --Real
print [-5^3,-(5)^3,(-5)^3,-(5^3)] --Integer
print [-5^^3,-(5)^^3,(-5)^^3,-(5^^3)] --Fractional
print [-5**3,-(5)**3,(-5)**3,-(5**3)] --Real
- Output:
[-25,-25,25,-25] [-25.0,-25.0,25.0,-25.0] [-25.0,-25.0,25.0,-25.0] [-125,-125,-125,-125] [-125.0,-125.0,-125.0,-125.0] [-125.0,-125.0,-125.0,-125.0]
J
APLs use a negative sign distinguished from minus as a different character. Underscore followed by a number specifies a negative number. APLs also process the operations from right to left, evaluating parenthesized expressions when the interpreter comes to them. In J, unary plus returns complex conjugate, which won't affect the outcome of this experiment.
format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ]) S=: 'x = {} p = {} -x^p {} -(x)^p {} (-x)^p {} -(x^p) {}' explicit=: dyad def 'S format~ 2 2 4 4 4 4 ":&> x,y,(-x^y),(-(x)^y),((-x)^y),(-(x^y))' tacit=: S format~ 2 2 4 4 4 4 ":&> [`]`([:-^)`([:-^)`((^~-)~)`([:-^)`:0 _2 explicit/\_5 2 _5 3 5 2 5 3 x = _5 p = 2 -x^p _25 -(x)^p _25 (-x)^p 25 -(x^p) _25 x = _5 p = 3 -x^p 125 -(x)^p 125 (-x)^p 125 -(x^p) 125 x = 5 p = 2 -x^p _25 -(x)^p _25 (-x)^p 25 -(x^p) _25 x = 5 p = 3 -x^p _125 -(x)^p _125 (-x)^p _125 -(x^p) _125 -:/ 1 0 2 |: _2(tacit ,: explicit)/\_5 2 _5 3 5 2 5 3 NB. the verbs produce matching results 1
Julia
In Julia, the ^ symbol is the power infix operator. The ^ operator has a higher precedence than the - operator, so -5^2 is -25 and (-5)^2 is 25.
for x in [-5, 5], p in [2, 3]
println("x is", lpad(x, 3), ", p is $p, -x^p is", lpad(-x^p, 4), ", -(x)^p is",
lpad(-(x)^p, 5), ", (-x)^p is", lpad((-x)^p, 5), ", -(x^p) is", lpad(-(x^p), 5))
end
- Output:
x is -5, p is 2, -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 x is -5, p is 3, -x^p is 125, -(x)^p is 125, (-x)^p is 125, -(x^p) is 125 x is 5, p is 2, -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 x is 5, p is 3, -x^p is-125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125
langur
writeln [-5^2, -(5)^2, (-5)^2, -(5^2)]
writeln [-5^3, -(5)^3, (-5)^3, -(5^3)]
- Output:
[-25, -25, 25, -25] [-125, -125, -125, -125]
Lua
Lua < 5.3 has a single double-precision numeric type. Lua >= 5.3 adds an integer numeric type. "^" is supported as an infix exponentiation operator for both types.
mathtype = math.type or type -- polyfill <5.3
function test(xs, ps)
for _,x in ipairs(xs) do
for _,p in ipairs(ps) do
print(string.format("%2.f %7s %2.f %7s %4.f %4.f %4.f %4.f", x, mathtype(x), p, mathtype(p), -x^p, -(x)^p, (-x)^p, -(x^p)))
end
end
end
print(" x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p)")
print("-- ------- -- ------- ------ ------ ------ ------")
test( {-5.,5.}, {2.,3.} ) -- "float" (or "number" if <5.3)
if math.type then -- if >=5.3
test( {-5,5}, {2,3} ) -- "integer"
end
- Output:
x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p) -- ------- -- ------- ------ ------ ------ ------ -5 float 2 float -25 -25 25 -25 -5 float 3 float 125 125 125 125 5 float 2 float -25 -25 25 -25 5 float 3 float -125 -125 -125 -125 -5 integer 2 integer -25 -25 25 -25 -5 integer 3 integer 125 125 125 125 5 integer 2 integer -25 -25 25 -25 5 integer 3 integer -125 -125 -125 -125
Maple
[-5**2,-(5)**2,(-5)**2,-(5**2)];
[-25, -25, 25, -25]
[-5**3,-(5)**3,(-5)**3,-(5**3)];
[-125, -125, -125, -125]
Mathematica / Wolfram Language
{-5^2, -(5)^2, (-5)^2, -(5^2)}
{-5^3, -(5)^3, (-5)^3, -(5^3)}
- Output:
{-25, -25, 25, -25} {-125, -125, -125, -125}
Nim
The infix exponentiation operator is defined in standard module “math”. Its precedence is less than that of unary “-” operator, so -5^2 is 25 and -(5^2) is -25.
import math, strformat
for x in [-5, 5]:
for p in [2, 3]:
echo &"x is {x:2}, ", &"p is {p:1}, ",
&"-x^p is {-x^p:4}, ", &"-(x)^p is {-(x)^p:4}, ",
&"(-x)^p is {(-x)^p:4}, ", &"-(x^p) is {-(x^p):4}"
- Output:
x is -5, p is 2, -x^p is 25, -(x)^p is 25, (-x)^p is 25, -(x^p) is -25 x is -5, p is 3, -x^p is 125, -(x)^p is 125, (-x)^p is 125, -(x^p) is 125 x is 5, p is 2, -x^p is 25, -(x)^p is 25, (-x)^p is 25, -(x^p) is -25 x is 5, p is 3, -x^p is -125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125
Pascal
Apart from the built-in (prefix) functions sqr (exponent = 2) and sqrt (exponent = 0.5) already defined in Standard “Unextended” Pascal (ISO standard 7185), Extended Pascal (ISO standard 10206) defines following additional (infix) operators:
program exponentiationWithInfixOperatorsInTheBase(output);
const
minimumWidth = 7;
fractionDigits = minimumWidth div 4 + 1;
procedure testIntegerPower(
{ `pow` can in fact accept `integer`, `real` and `complex`. }
protected base: integer;
{ For `pow` the `exponent` _has_ to be an `integer`. }
protected exponent: integer
);
begin
writeLn('=====> testIntegerPower <=====');
writeLn(' base = ', base:minimumWidth);
writeLn(' exponent = ', exponent:minimumWidth);
{ Note: `exponent` may not be negative if `base` is zero! }
writeLn(' -base pow exponent = ', -base pow exponent:minimumWidth);
writeLn('-(base) pow exponent = ', -(base) pow exponent:minimumWidth);
writeLn('(-base) pow exponent = ', (-base) pow exponent:minimumWidth);
writeLn('-(base pow exponent) = ', -(base pow exponent):minimumWidth)
end;
procedure testRealPower(
{ `**` actually accepts all data types (`integer`, `real`, `complex`). }
protected base: real;
{ The `exponent` in an `**` expression will be, if applicable, }
{ _promoted_ to a `real` value approximation. }
protected exponent: integer
);
begin
writeLn('======> testRealPower <======');
writeLn(' base = ', base:minimumWidth:fractionDigits);
writeLn(' exponent = ', exponent:pred(minimumWidth, succ(fractionDigits)));
if base > 0.0 then
begin
{ The result of `base ** exponent` is a `complex` value }
{ `base` is a `complex` value, `real` otherwise. }
writeLn(' -base ** exponent = ', -base ** exponent:minimumWidth:fractionDigits);
writeLn('-(base) ** exponent = ', -(base) ** exponent:minimumWidth:fractionDigits);
writeLn('(-base) ** exponent = illegal');
writeLn('-(base ** exponent) = ', -(base ** exponent):minimumWidth:fractionDigits)
end
else
begin
{ “negative” zero will not alter the sign of the value. }
writeLn(' -base ** exponent = ', -base pow exponent:minimumWidth:fractionDigits);
writeLn('-(base) ** exponent = ', -(base) pow exponent:minimumWidth:fractionDigits);
writeLn('(-base) ** exponent = ', (-base) pow exponent:minimumWidth:fractionDigits);
writeLn('-(base ** exponent) = ', -(base pow exponent):minimumWidth:fractionDigits)
end
end;
{ === MAIN =================================================================== }
begin
testIntegerPower(-5, 2);
testIntegerPower(+5, 2);
testIntegerPower(-5, 3);
testIntegerPower( 5, 3);
testRealPower(-5.0, 2);
testRealPower(+5.0, 2);
testRealPower(-5E0, 3);
testRealPower(+5E0, 3)
end.
- Output:
=====> testIntegerPower <===== base = -5 exponent = 2 -base pow exponent = -25 -(base) pow exponent = -25 (-base) pow exponent = 25 -(base pow exponent) = -25 =====> testIntegerPower <===== base = 5 exponent = 2 -base pow exponent = -25 -(base) pow exponent = -25 (-base) pow exponent = 25 -(base pow exponent) = -25 =====> testIntegerPower <===== base = -5 exponent = 3 -base pow exponent = 125 -(base) pow exponent = 125 (-base) pow exponent = 125 -(base pow exponent) = 125 =====> testIntegerPower <===== base = 5 exponent = 3 -base pow exponent = -125 -(base) pow exponent = -125 (-base) pow exponent = -125 -(base pow exponent) = -125 ======> testRealPower <====== base = -5.00 exponent = 2 -base ** exponent = -25.00 -(base) ** exponent = -25.00 (-base) ** exponent = 25.00 -(base ** exponent) = -25.00 ======> testRealPower <====== base = 5.00 exponent = 2 -base ** exponent = -25.00 -(base) ** exponent = -25.00 (-base) ** exponent = illegal -(base ** exponent) = -25.00 ======> testRealPower <====== base = -5.00 exponent = 3 -base ** exponent = 125.00 -(base) ** exponent = 125.00 (-base) ** exponent = 125.00 -(base ** exponent) = 125.00 ======> testRealPower <====== base = 5.00 exponent = 3 -base ** exponent = -125.00 -(base) ** exponent = -125.00 (-base) ** exponent = illegal -(base ** exponent) = -125.00
Since there are two different power operators available, both accepting operands of different data types, having different limits, and yielding different data types, it was not sensible to produce a table similar to other entries on this page.
Perl
Use the module Sub::Infix to define a custom operator. Note that the bracketing punctuation controls the precedence level. Results structured same as in Raku example.
use strict;
use warnings;
use Sub::Infix;
BEGIN { *e = infix { $_[0] ** $_[1] } }; # operator needs to be defined at compile time
my @eqns = ('1 + -$xOP$p', '1 + (-$x)OP$p', '1 + (-($x)OP$p)', '(1 + -$x)OP$p', '1 + -($xOP$p)');
for my $op ('**', '/e/', '|e|') {
for ( [-5, 2], [-5, 3], [5, 2], [5, 3] ) {
my( $x, $p, $eqn ) = @$_;
printf 'x: %2d p: %2d |', $x, $p;
$eqn = s/OP/$op/gr and printf '%17s %4d |', $eqn, eval $eqn for @eqns;
print "\n";
}
print "\n";
}
- Output:
x: -5 p: 2 | 1 + -$x**$p -24 | 1 + (-$x)**$p 26 | 1 + (-($x)**$p) -24 | (1 + -$x)**$p 36 | 1 + -($x**$p) -24 | x: -5 p: 3 | 1 + -$x**$p 126 | 1 + (-$x)**$p 126 | 1 + (-($x)**$p) 126 | (1 + -$x)**$p 216 | 1 + -($x**$p) 126 | x: 5 p: 2 | 1 + -$x**$p -24 | 1 + (-$x)**$p 26 | 1 + (-($x)**$p) -24 | (1 + -$x)**$p 16 | 1 + -($x**$p) -24 | x: 5 p: 3 | 1 + -$x**$p -124 | 1 + (-$x)**$p -124 | 1 + (-($x)**$p) -124 | (1 + -$x)**$p -64 | 1 + -($x**$p) -124 | x: -5 p: 2 | 1 + -$x/e/$p 26 | 1 + (-$x)/e/$p 26 | 1 + (-($x)/e/$p) 26 | (1 + -$x)/e/$p 36 | 1 + -($x/e/$p) -24 | x: -5 p: 3 | 1 + -$x/e/$p 126 | 1 + (-$x)/e/$p 126 | 1 + (-($x)/e/$p) 126 | (1 + -$x)/e/$p 216 | 1 + -($x/e/$p) 126 | x: 5 p: 2 | 1 + -$x/e/$p 26 | 1 + (-$x)/e/$p 26 | 1 + (-($x)/e/$p) 26 | (1 + -$x)/e/$p 16 | 1 + -($x/e/$p) -24 | x: 5 p: 3 | 1 + -$x/e/$p -124 | 1 + (-$x)/e/$p -124 | 1 + (-($x)/e/$p) -124 | (1 + -$x)/e/$p -64 | 1 + -($x/e/$p) -124 | x: -5 p: 2 | 1 + -$x|e|$p 36 | 1 + (-$x)|e|$p 36 | 1 + (-($x)|e|$p) 26 | (1 + -$x)|e|$p 36 | 1 + -($x|e|$p) -24 | x: -5 p: 3 | 1 + -$x|e|$p 216 | 1 + (-$x)|e|$p 216 | 1 + (-($x)|e|$p) 126 | (1 + -$x)|e|$p 216 | 1 + -($x|e|$p) 126 | x: 5 p: 2 | 1 + -$x|e|$p 16 | 1 + (-$x)|e|$p 16 | 1 + (-($x)|e|$p) 26 | (1 + -$x)|e|$p 16 | 1 + -($x|e|$p) -24 | x: 5 p: 3 | 1 + -$x|e|$p -64 | 1 + (-$x)|e|$p -64 | 1 + (-($x)|e|$p) -124 | (1 + -$x)|e|$p -64 | 1 + -($x|e|$p) -124 |
Phix
Phix has a power() function instead of an infix operator, hence there are only two possible syntaxes, with the obvious outcomes.
(Like Go, Phix does not support operator overloading or definition at all.)
for x=-5 to 5 by 10 do for p=2 to 3 do printf(1,"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n",{x,p,power(-x,p),-power(x,p)}) end for end for
- Output:
x = -5, p = 2, power(-x,p) = 25, -power(x,p) = -25 x = -5, p = 3, power(-x,p) = 125, -power(x,p) = 125 x = 5, p = 2, power(-x,p) = 25, -power(x,p) = -25 x = 5, p = 3, power(-x,p) = -125, -power(x,p) = -125
QB64
For x = -5 To 5 Step 10
For p = 2 To 3
Print "x = "; x; " p ="; p; " ";
Print Using "-x^p is ####"; -x ^ p;
Print Using ", -(x)^p is ####"; -(x) ^ p;
Print Using ", (-x)^p is ####"; (-x) ^ p;
Print Using ", -(x^p) is ####"; -(x ^ p)
Next
Next
- Output:
x = -5 p = 2 -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 x = -5 p = 3 -x^p is 125, -(x)^p is 125, (-x)^p is 125, -(x^p) is 125 x = 5 p = 2 -x^p is -25, -(x)^p is -25, (-x)^p is 25, -(x^p) is -25 x = 5 p = 3 -x^p is -125, -(x)^p is -125, (-x)^p is -125, -(x^p) is -125
R
expressions <- alist(-x ^ p, -(x) ^ p, (-x) ^ p, -(x ^ p))
x <- c(-5, -5, 5, 5)
p <- c(2, 3, 2, 3)
output <- data.frame(x,
p,
setNames(lapply(expressions, eval), sapply(expressions, deparse)),
check.names = FALSE)
print(output, row.names = FALSE)
- Output:
x p -x^p -(x)^p (-x)^p -(x^p) -5 2 -25 -25 25 -25 -5 3 125 125 125 125 5 2 -25 -25 25 -25 5 3 -125 -125 -125 -125
Raku
In Raku by default, infix exponentiation binds tighter than unary negation. It is trivial however to define your own infix operators with whatever precedence level meets the needs of your program.
A slight departure from the task specs. Use 1 + {expression}
rather than just {expression}
to better demonstrate the relative precedence levels. Where {expression}
is one of:
-x{exponential operator}p
-(x){exponential operator}p
((-x){exponential operator}p)
-(x{exponential operator}p)
Also add a different grouping: (1 + -x){exponential operator}p
sub infix:<↑> is looser(&prefix:<->) { $^a ** $^b }
sub infix:<∧> is looser(&infix:<->) { $^a ** $^b }
for
('Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.',
'1 + -$x**$p', {1 + -$^a**$^b}, '1 + (-$x)**$p', {1 + (-$^a)**$^b}, '1 + (-($x)**$p)', {1 + (-($^a)**$^b)},
'(1 + -$x)**$p', {(1 + -$^a)**$^b}, '1 + -($x**$p)', {1 + -($^a**$^b)}),
("\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.",
'1 + -$x↑$p ', {1 + -$^a↑$^b}, '1 + (-$x)↑$p ', {1 + (-$^a)↑$^b}, '1 + (-($x)↑$p) ', {1 + (-($^a)↑$^b)},
'(1 + -$x)↑$p ', {(1 + -$^a)↑$^b}, '1 + -($x↑$p) ', {1 + -($^a↑$^b)}),
("\nEven more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.",
'1 + -$x∧$p ', {1 + -$^a∧$^b}, '1 + (-$x)∧$p ', {1 + (-$^a)∧$^b}, '1 + (-($x)∧$p) ', {1 + (-($^a)∧$^b)},
'(1 + -$x)∧$p ', {(1 + -$^a)∧$^b}, '1 + -($x∧$p) ', {1 + -($^a∧$^b)})
-> $case {
my ($title, @operations) = $case<>;
say $title;
for -5, 5 X 2, 3 -> ($x, $p) {
printf "x = %2d p = %d", $x, $p;
for @operations -> $label, &code { print " │ $label = " ~ $x.&code($p).fmt('%4d') }
say ''
}
}
- Output:
Default precedence: infix exponentiation is tighter (higher) precedence than unary negation. x = -5 p = 2 │ 1 + -$x**$p = -24 │ 1 + (-$x)**$p = 26 │ 1 + (-($x)**$p) = -24 │ (1 + -$x)**$p = 36 │ 1 + -($x**$p) = -24 x = -5 p = 3 │ 1 + -$x**$p = 126 │ 1 + (-$x)**$p = 126 │ 1 + (-($x)**$p) = 126 │ (1 + -$x)**$p = 216 │ 1 + -($x**$p) = 126 x = 5 p = 2 │ 1 + -$x**$p = -24 │ 1 + (-$x)**$p = 26 │ 1 + (-($x)**$p) = -24 │ (1 + -$x)**$p = 16 │ 1 + -($x**$p) = -24 x = 5 p = 3 │ 1 + -$x**$p = -124 │ 1 + (-$x)**$p = -124 │ 1 + (-($x)**$p) = -124 │ (1 + -$x)**$p = -64 │ 1 + -($x**$p) = -124 Easily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation. x = -5 p = 2 │ 1 + -$x↑$p = 26 │ 1 + (-$x)↑$p = 26 │ 1 + (-($x)↑$p) = 26 │ (1 + -$x)↑$p = 36 │ 1 + -($x↑$p) = -24 x = -5 p = 3 │ 1 + -$x↑$p = 126 │ 1 + (-$x)↑$p = 126 │ 1 + (-($x)↑$p) = 126 │ (1 + -$x)↑$p = 216 │ 1 + -($x↑$p) = 126 x = 5 p = 2 │ 1 + -$x↑$p = 26 │ 1 + (-$x)↑$p = 26 │ 1 + (-($x)↑$p) = 26 │ (1 + -$x)↑$p = 16 │ 1 + -($x↑$p) = -24 x = 5 p = 3 │ 1 + -$x↑$p = -124 │ 1 + (-$x)↑$p = -124 │ 1 + (-($x)↑$p) = -124 │ (1 + -$x)↑$p = -64 │ 1 + -($x↑$p) = -124 Even more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction. x = -5 p = 2 │ 1 + -$x∧$p = 36 │ 1 + (-$x)∧$p = 36 │ 1 + (-($x)∧$p) = 26 │ (1 + -$x)∧$p = 36 │ 1 + -($x∧$p) = -24 x = -5 p = 3 │ 1 + -$x∧$p = 216 │ 1 + (-$x)∧$p = 216 │ 1 + (-($x)∧$p) = 126 │ (1 + -$x)∧$p = 216 │ 1 + -($x∧$p) = 126 x = 5 p = 2 │ 1 + -$x∧$p = 16 │ 1 + (-$x)∧$p = 16 │ 1 + (-($x)∧$p) = 26 │ (1 + -$x)∧$p = 16 │ 1 + -($x∧$p) = -24 x = 5 p = 3 │ 1 + -$x∧$p = -64 │ 1 + (-$x)∧$p = -64 │ 1 + (-($x)∧$p) = -124 │ (1 + -$x)∧$p = -64 │ 1 + -($x∧$p) = -124
REXX
/*REXX program shows exponentition with an infix operator (implied and/or specified).*/
_= '─'; ! = '║'; mJunct= '─╫─'; bJunct= '─╨─' /*define some special glyphs. */
say @(' x ', 5) @(" p ", 5) !
say @('value', 5) @("value", 5) copies(! @('expression',10) @("result",6)" ", 4)
say @('' , 5, _) @("", 5, _)copies(mJunct || @('', 10, _) @("", 6, _) , 4)
do x=-5 to 5 by 10 /*assign -5 and 5 to X. */
do p= 2 to 3 /*assign 2 and 3 to P. */
a = -x**p ; b = -(x)**p ; c = (-x)**p ; d = -(x**p)
ae= '-x**p'; be= "-(x)**p"; ce= '(-x)**p'; de= "-(x**p)"
say @(x,5) @(p,5) ! @(ae, 10) right(a, 5)" " ,
! @(be, 10) right(b, 5)" " ,
! @(ce, 10) right(c, 5)" " ,
! @(de, 10) right(d, 5)
end /*p*/
end /*x*/
say @('' , 5, _) @('', 5, _)copies(bJunct || @('', 10, _) @('', 6, _) , 4)
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg txt, w, fill; if fill=='' then fill= ' '; return center( txt, w, fill)
- output when using the internal default input:
x p ║ value value ║ expression result ║ expression result ║ expression result ║ expression result ───── ──────╫─────────── ───────╫─────────── ───────╫─────────── ───────╫─────────── ────── -5 2 ║ -x**p 25 ║ -(x)**p 25 ║ (-x)**p 25 ║ -(x**p) -25 -5 3 ║ -x**p 125 ║ -(x)**p 125 ║ (-x)**p 125 ║ -(x**p) 125 5 2 ║ -x**p 25 ║ -(x)**p 25 ║ (-x)**p 25 ║ -(x**p) -25 5 3 ║ -x**p -125 ║ -(x)**p -125 ║ (-x)**p -125 ║ -(x**p) -125 ───── ──────╨─────────── ───────╨─────────── ───────╨─────────── ───────╨─────────── ──────
RPL
Using infix exponentiation as required, even if not RPLish:
≪ → x p ≪ { 'x' 'p' '-x^p' '-(x)^p' '(-x)^p' '-(x^p)' } 1 DO GETI EVAL ROT ROT UNTIL DUP 1 == END DROP 7 ROLLD 6 →LIST ≫ ≫ 'SHOXP' STO
- Input:
-5 2 SHOXP -5 3 SHOXP 5 2 SHOXP 5 3 SHOXP
- Output:
8: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } 7: { -5 2 -25 -25 25 -25 } 6: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } 5: { -5 3 125 125 125 125 } 4: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } 3: { 5 2 -25 -25 25 -25 } 2: { 'x' 'p' '-x^p' '-x^p' '(-x)^p' '-x^p' } 1: { 5 3 -125 -125 -125 -125 }
Original infix expressions (see code above in bold characters) have been simplified by the interpreter when storing the program. In reverse Polish notation, there is only one way to answer the task:
≪ → x p ≪ x NEG p ^ ≫ ≫ 'SHOXP' STO
Ruby
nums = [-5, 5]
pows = [2, 3]
nums.product(pows) do |x, p|
puts "x = #{x} p = #{p}\t-x**p #{-x**p}\t-(x)**p #{-(x)**p}\t(-x)**p #{ (-x)**p}\t-(x**p) #{-(x**p)}"
end
- Output:
x = -5 p = 2 -x**p -25 -(x)**p -25 (-x)**p 25 -(x**p) -25 x = -5 p = 3 -x**p 125 -(x)**p 125 (-x)**p 125 -(x**p) 125 x = 5 p = 2 -x**p -25 -(x)**p -25 (-x)**p 25 -(x**p) -25 x = 5 p = 3 -x**p -125 -(x)**p -125 (-x)**p -125 -(x**p) -125
Python
from itertools import product
xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()
print('Integer variable exponentiation')
for x, p in product(xx, pp):
print(f' x,p = {x:2},{p}; ', end=' ')
x, p = int(x), int(p)
print('; '.join(f"{t} =={eval(t):4}" for t in texts))
print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
texts2 = [t.replace(X, x).replace(P, p) for t in texts]
print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
- Output:
Integer variable exponentiation x,p = -5,2; -x**p == -25; -(x)**p == -25; (-x)**p == 25; -(x**p) == -25 x,p = -5,3; -x**p == 125; -(x)**p == 125; (-x)**p == 125; -(x**p) == 125 x,p = +5,2; -x**p == -25; -(x)**p == -25; (-x)**p == 25; -(x**p) == -25 x,p = +5,3; -x**p ==-125; -(x)**p ==-125; (-x)**p ==-125; -(x**p) ==-125 Bonus integer literal exponentiation 5**2 == 25; - 5**2 == -25; -( 5)**2 == -25; (- 5)**2 == 25; -( 5**2) == -25 5**3 == 125; - 5**3 ==-125; -( 5)**3 ==-125; (- 5)**3 ==-125; -( 5**3) ==-125 -5**2 == -25; --5**2 == 25; -(-5)**2 == -25; (--5)**2 == 25; -(-5**2) == 25 -5**3 ==-125; --5**3 == 125; -(-5)**3 == 125; (--5)**3 == 125; -(-5**3) == 125 +5**2 == 25; -+5**2 == -25; -(+5)**2 == -25; (-+5)**2 == 25; -(+5**2) == -25 +5**3 == 125; -+5**3 ==-125; -(+5)**3 ==-125; (-+5)**3 ==-125; -(+5**3) ==-125
Smalltalk
Smalltalk has no prefix operator for negation. To negate, you have to send the number a "negated" message, which has higher precedence than any binary message. Literal constants may have a sign (which is not an operation, but part of the constant).
a := 2.
b := 3.
Transcript show:'-5**2 => '; showCR: -5**2.
Transcript show:'-5**a => '; showCR: -5**a.
Transcript show:'-5**b => '; showCR: -5**b.
Transcript show:'5**2 => '; showCR: 5**2.
Transcript show:'5**a => '; showCR: 5**a.
Transcript show:'5**b => '; showCR: 5**b.
" Transcript show:'-(5**b) => '; showCR: -(5**b). -- invalid: syntax error "
" Transcript show:'5**-b => '; showCR: 5**-b. -- invalid: syntax error "
Using the "negated" message:
Transcript show:'5 negated**2 => '; showCR: 5 negated**2. "negates 5"
Transcript show:'5 negated**3 => '; showCR: 5 negated**3.
Transcript show:'5**2 negated => '; showCR: 5**2 negated. "negates 2"
Transcript show:'5**3 negated => '; showCR: 5**3 negated. "negates 3"
Transcript show:'5 negated**a => '; showCR: 5 negated**a.
Transcript show:'5 negated**b => '; showCR: 5 negated**b.
Transcript show:'5**a negated => '; showCR: 5**a negated.
Transcript show:'5**b negated => '; showCR: 5**b negated.
Transcript show:'(5**a) negated => '; showCR: (5**a) negated.
Transcript show:'(5**b) negated => '; showCR: (5**b) negated.
Transcript show:'(-5**a) negated => '; showCR: (-5**a) negated.
Transcript show:'(-5**b) negated => '; showCR: (-5**b) negated.
Transcript show:'-5 negated**2 => '; showCR: -5 negated**2. "negates the negative 5"
Transcript show:'-5 negated**3 => '; showCR: -5 negated**3.
- Output:
-5**2 => 25 -5**a => 25 -5**b => -125 5**2 => 25 5**a => 25 5**b => 125 5 negated**2 => 25 5 negated**3 => -125 5**2 negated => (1/25) 5**3 negated => (1/125) 5 negated**a => 25 5 negated**b => -125 5**a negated => (1/25) 5**b negated => (1/125) (5**a) negated => -25 (5**b) negated => -125 (-5**a) negated => -25 (-5**b) negated => 125 -5 negated**2 => 25 -5 negated**3 => 125
Wren
Wren uses the pow() method for exponentiation of numbers and, whilst it supports operator overloading, there is no way of adding a suitable infix operator to the existing Num class or inheriting from that class.
However, what we can do is to wrap Num objects in a new Num2 class and then add exponentiation and unary minus operators to that.
Ideally what we'd like to do is to use a new operator such as '**' for exponentiation (because '^' is the bitwise exclusive or operator) but we can only overload existing operators with their existing precedence and so, for the purposes of this task, '^' is the only realistic choice.
import "./fmt" for Fmt
class Num2 {
construct new(n) { _n = n }
n { _n}
^(exp) {
if (exp is Num2) exp = exp.n
return Num2.new(_n.pow(exp))
}
- { Num2.new(-_n) }
toString { _n.toString }
}
var ops = ["-x^p", "-(x)^p", "(-x)^p", "-(x^p)"]
for (x in [Num2.new(-5), Num2.new(5)]) {
for (p in [Num2.new(2), Num2.new(3)]) {
Fmt.write("x = $2s p = $s | ", x, p)
Fmt.write("$s = $4s | ", ops[0], -x^p)
Fmt.write("$s = $4s | ", ops[1], -(x)^p)
Fmt.write("$s = $4s | ", ops[2], (-x)^p)
Fmt.print("$s = $4s", ops[3], -(x^p))
}
}
- Output:
x = -5 p = 2 | -x^p = 25 | -(x)^p = 25 | (-x)^p = 25 | -(x^p) = -25 x = -5 p = 3 | -x^p = 125 | -(x)^p = 125 | (-x)^p = 125 | -(x^p) = 125 x = 5 p = 2 | -x^p = 25 | -(x)^p = 25 | (-x)^p = 25 | -(x^p) = -25 x = 5 p = 3 | -x^p = -125 | -(x)^p = -125 | (-x)^p = -125 | -(x^p) = -125
- Programming Tasks
- Solutions by Programming Task
- Ada
- ALGOL 68
- AWK
- BASIC
- Applesoft BASIC
- BASIC256
- Gambas
- QBasic
- Run BASIC
- True BASIC
- PureBasic
- XBasic
- Yabasic
- EasyLang
- F Sharp
- Factor
- FreeBASIC
- Go
- Haskell
- J
- Julia
- Langur
- Lua
- Maple
- Mathematica
- Wolfram Language
- Nim
- Pascal
- Perl
- Phix
- Phix/basics
- QB64
- R
- Raku
- REXX
- RPL
- Ruby
- Python
- Smalltalk
- Wren
- Wren-fmt