Exponentiation order

From Rosetta Code
Revision as of 20:15, 30 March 2014 by Steenslag (talk | contribs) (→‎{{header|Ruby}}: Added Ruby entry.)
Exponentiation order is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

This task will demonstrate the order of exponentiation (xy) when there are multiple exponents. (Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, or some such for exponentiation.)

Task requirements

Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.

Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):

  • 5**3**2
  • (5**3)**2
  • 5**(3**2)

If there are other methods (or formats) of multiple exponentiations, show them as well.

See also

C

C does not have an exponentiation operator. The caret operator '^' performs xor bitwise operation in C. The function pow in the standard C Math library takes 2 arguments.

Expressions in C are evaluated by RPN. The RPNs of 5^3^2 and 5^(3^2) are the same and thus also their pow expressions. <lang C> /*Abhishek Ghosh, 20th March 2014, Rotterdam*/

include<stdio.h>

  1. include<math.h>

int main() { printf("\n5 ^ 3 ^ 2 = %.0f",pow(5,pow(3,2))); /*.0f suppresses decimal output*/ printf("\n(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2)); printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2)));

return 0; } </lang>

Output:

5 ^ 3 ^ 2   = 1953125
(5 ^ 3) ^ 2 = 15625
5 ^ (3 ^ 2) = 1953125

D

<lang d>void main() {

   import std.stdio, std.math, std.algorithm;
   writefln("5 ^^ 3 ^^ 2          = %7d", 5 ^^ 3 ^^ 2);
   writefln("(5 ^^ 3) ^^ 2        = %7d", (5 ^^ 3) ^^ 2);
   writefln("5 ^^ (3 ^^ 2)        = %7d", 5 ^^ (3 ^^ 2));
   writefln("[5, 3, 2].reduce!pow = %7d", [5, 3, 2].reduce!pow);

}</lang>

Output:
5 ^^ 3 ^^ 2          = 1953125
(5 ^^ 3) ^^ 2        =   15625
5 ^^ (3 ^^ 2)        = 1953125
[5, 3, 2].reduce!pow =   15625

Perl 6

<lang perl6>sub demo($x) { say " $x\t───► ", EVAL $x }

demo '5**3**2'; # show ** is right associative demo '(5**3)**2'; demo '5**(3**2)';

demo '[**] 5,3,2'; # reduction form, show only final result demo '[\**] 5,3,2'; # triangle reduction, show growing results</lang>

Output:
  5**3**2	───► 1953125
  (5**3)**2	───► 15625
  5**(3**2)	───► 1953125
  [**] 5,3,2	───► 1953125
  [\**] 5,3,2	───► 2 9 1953125

Note that the reduction forms automatically go right-to-left because the base operator is right-associative. Most other operators are left-associative and would automatically reduce left-to-right instead.

While it is possible to define your own postfix operators to do exponentiation, Unicode does not have multilevel subscripts, and postfixes are always evaluated from inside out, so you can't stack them and expect right associativity: <lang perl6>sub postfix:<²>($n) { $n * $n } sub postfix:<³>($n) { $n * $n * $n }

demo '(5³)²'; demo '5³²';</lang>

Output:
  (5³)²	───► 15625
  5³²	───► 15625

(Not to mention the fact that the form without parentheses looks like you're trying to raise something to the 32nd power. Nor are you even allowed to parenthesize it the other way: 5(³²) would be a syntax error. Despite all that, for programs that do a lot of squaring or cubing, the postfix forms can enhance both readability and concision.)

Python

<lang python>>>> 5**3**2 1953125 >>> (5**3)**2 15625 >>> 5**(3**2) 1953125 >>> # The following is not normally done >>> try: from functools import reduce # Py3K except: pass

>>> reduce(pow, (5, 3, 2)) 15625 >>> </lang>

Racket

<lang racket>#lang racket

5**3**2 depends on associativity of **
Racket's (scheme's) prefix function
calling syntax only allows for pairs of arguments for expt.
So no can do for 5**3**2
(5**3)**2

(displayln "prefix") (expt (expt 5 3) 2)

(5**3)**2

(expt 5 (expt 3 2))

There is also a less-used infix operation (for all functions, not just expt)... which I suppose
might do with an airing. But fundamentally nothing changes.

(displayln "\"in\"fix") ((5 . expt . 3) . expt . 2) (5 . expt . (3 . expt . 2))

everyone's doing a reduction, it seems

(displayln "reduction") (require (only-in srfi/1 reduce reduce-right)) (reduce expt 1 '(5 3 2)) (reduce-right expt 1 '(5 3 2))</lang>

Output:
prefix
15625
1953125
"in"fix
15625
1953125
reduction
14134776518227074636666380005943348126619871175004951664972849610340958208
1953125

REXX

<lang rexx>/*REXX program demonstrates various ways of multiple exponentiations. */ /*┌────────────────────────────────────────────────────────────────────┐

 │ The REXX language uses      **      for exponention.               │
 │                   Also,    *  *     can be used.                   │
 └────────────────────────────────────────────────────────────────────┘*/

say ' 5**3**2 ───► ' 5**3**2 say ' (5**3)**2 ───► ' (5**3)**2 say ' 5**(3**2) ───► ' 5**(3**2)

                                      /*stick a fork in it, we're done.*/</lang>

output

   5**3**2   ───►  15625
   (5**3)**2 ───►  15625
   5**(3**2) ───►  1953125

Ruby

<lang ruby>ar = ["5**3**2", "(5**3)**2", "5**(3**2)", "[5,3,2].inject(:**)"] ar.each{|exp| puts "#{exp}:\t#{eval exp}"} </lang>

Output:
5**3**2:	1953125
(5**3)**2:	15625
5**(3**2):	1953125
[5,3,2].inject(:**):	15625

Tcl

<lang tcl>foreach expression {5**3**2 (5**3)**2 5**(3**2)} {

   puts "${expression}:\t[expr $expression]"

}</lang>

Output:
5**3**2:	1953125
(5**3)**2:	15625
5**(3**2):	1953125

There's also a binary pow() expression function that always converts its arguments to floating point numbers and then applies the exponentiation operation; it's now largely obsolete because of the ** operator, but is retained for backward compatibility with older programs.