tags:

views:

72

answers:

4

I am writing a little home-made calculator for integers and it includes two binary operators, 'pow' and 'root'. The 'pow' operator evaluates (left operand) ^ (right operand), and the 'root' operator finds the largest number n such that n ^ (left operand) <= (right operand).

Assuming this isn't an absurd thing to do, what should the precedence of these operators be? Currently I have them at equal precedence so strings such as

3 root 1500 pow 7

evaluate left to right. Is this right? Should I put this question on mathoverflow?

+4  A: 

pow and root are essentially the same operation, expressed differently (similar to binary + and -). I.e., sqrt(a) is the same as pow(a, 0.5), just like a + b is the same as a - (-b). So I'd say they should have equal precedence, and hence be evaluated left-to-right.

tdammers
+3  A: 

In most other languages, exponentiation goes from right to left. This is because (a^b)^c = a^(b*c) != a^(b^c) . See for example the section for the power operator in Python (section 5.4)

deinst
+1. Combined with the fact that `a root b == a pow 1/b`, that yields the answer: they should have same precedence, and be evaluated from right to left.
Alexandre C.
@Alexandre - the OP chose root such that 'a root b == b pow 1/a'
Ralph Rickenbach
+1  A: 

pow and root mathematically have the same precedence, as you can see here:

The standard order of operations, or precedence, is expressed in the following chart.

  • exponents and roots
  • multiplication and division
  • addition and subtraction

As others said

3 root 1500 = 1500 pow (1/3)

Therefore they are inverse functions. Inverse functions have same precedence.

The order of your operands is quite unusual too. I would prefer 1500 root 3 to be the largest integer <= cubic root of 1500.

Ralph Rickenbach
Thank you. I'll ruminate for a while about the order of the operands, as you suggest.
Brian Hooper
I've thought about it, and decided to leave it the way it is. I think, when entering these expressions, cube root of something, fourth root of something, not something to the quarter. Evaluating left to right means this should be OK.
Brian Hooper
+1  A: 

Precedence seems fine in this particular case - you'll have issues with associativity which could act as precedence equivalent in some cases. The reason is that you made args to root reversed compared to pow which we tend to view as a "natural" order - left arg is subject to action by the right arg and yuour root is really just the pow to 1/y.

So, you may need to experiment a bit with more complex expressions like A root B root C pow D root G etc. and OTOH it would seem much better if you kept args for root in the same order as pow.

ZXX