Pow operator precedence
bearophile
bearophileHUGS at lycos.com
Fri Jan 13 12:29:46 PST 2012
Manu:
> What are you working on if I may ask?
Bioinformatics, exploratory programing, simulations, data munging, hardening of slow scripts, data visualization, data mining, optimization of some tasks, faster routines for dynamic code written by other people, and more.
> I do tend to write a lot of very
> maths-intensive code (physics, rendering, lighting), and I almost never
> find myself using any sort of pow, other than ^2, which I'm perfectly happy
> to type x*x.
The problem is that often you don't have a "x", but a "long_named_variable", so you have to write long_named_variable * long_named_variable. And often you have to compute an expression to square, so if you don't want to use a temporary variable you have to duplicate the expression. This is bug-prone and noisy.
Other cases:
1 << 5 ==> 2 ^^ 5 (more readable)
sqrt(3.5) ==> 3.5 ^^ 0.5
Sometimes better:
return ((p1.x - p2.x) ^^ 2 + (p1.y - p2.y) ^^ 2) ^^ 0.5;
10, 100, 1000, ... ==> map!(p => 10 ^^ p)(iota(2, ...))
You are allowed to write matrix code that overloads ^^ too.
DMD replaces x^^2 and x^^3 with inlined x**x and x*x*x, so it's better than using pow efficiency-wise. DMD knows few other exponent rules that applies as tricks, that I think pow() doesn't use. And programmers usually don't use pow to square a variable, while D programmers feel natural to use ^^ to square. So comparing the use cases of pow with ^^ is wrong.
I suggest you to start using ^^ in your D2 code and you will find it more and more useful.
I have now counted about 730 distinct usages of ^^ operator in the D2 code I have written and I am keeping my hands on at the moment. The real number is probably over 800. You are not going to deprecate it.
> Realistically, how often do you cube? It's extremely rare in my experience.
^^3 is not common.
Bye,
bearophile
More information about the Digitalmars-d
mailing list