Simple operator associativity and precedence rules (was: 2**2**2**2**2 wrong? Bug?)
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue Jul 10 04:41:54 EDT 2007
On Tue, 10 Jul 2007 18:05:49 +1000, Ben Finney wrote:
> I have never gone wrong with mathematical expressions since I reduced
> the set of operator associativity and precedence rules to these:
>
> 1. Addition and subtraction have the same precedence, and are
> left-to-right associative
>
> 2. Multiplication and division have the same precedence, and are
> left-to-right associative
>
> 3. Use parentheses to make explicit all other precedence and
> associativity
>
> The specific programming language I use at any given moment might follow
> more complex rules, but I ignore them in favour of the above set. I thus
> spend less time uselessly thinking about tasks I should be delegating to
> explicit expression syntax, and am never surprised by a misunderstood
> mathematical associativity or precedence rule.
However... floating point issues can still bite you. _Neither_ floating
point addition nor multiplication are associative, or rather, they are
not *always* associative. And it doesn't take weird examples, complicated
formulae, or wildly differing numbers to find examples:
>>> 0.1*(0.2*0.3) == (0.1*0.2)*0.3
False
>>> 0.1+(0.2+0.3) == (0.1+0.2)+0.3
False
(Depending on the version of Python, operating system, chip set,
underlying C libraries and solar tides, your millage may vary.)
The difference between the left and right hand sides are small, but real.
Or rather, float. *wink*
--
Steven.
More information about the Python-list
mailing list