December 7, 2011
Jon McLoone, International Business & Strategic Development
When people tell me that Mathematica isn’t fast enough, I usually ask to see the offending code and often find that the problem isn’t a lack in Mathematica’s performance, but sub-optimal use of Mathematica. I thought I would share the list of things that I look for first when trying to optimize Mathematica code.
1. Use floating-point numbers if you can, and use them early.
Of the most common issues that I see when I review slow code is that the programmer has inadvertently asked Mathematica to do things more carefully than needed. Unnecessary use of exact arithmetic is the most common case.
In most numerical software, there is no such thing as exact arithmetic. 1/3 is the same thing as 0.33333333333333. That difference can be pretty important when you hit nasty, numerically unstable problems, but in the majority of tasks, floating-point numbers are good enough and, importantly, much faster. In Mathematica any number with a decimal point and less than 16 digits of input is automatically treated as a machine float, so always use the decimal point if you want speed ahead of accuracy (e.g. enter a third as 1./3.). Here is a simple example where working with floating-point numbers is nearly 50.6 times faster than doing the computation exactly and then converting the result to a decimal afterward. And in this case it gets the same result.
![N[Det[Table[1/(1 + Abs[i - j]), {i, 1, 150}, {j, 1, 150}]]] // AbsoluteTiming N[Det[Table[1/(1 + Abs[i - j]), {i, 1, 150}, {j, 1, 150}]]] // AbsoluteTiming](http://blog.wolfram.com/data/uploads/2011/12/10Tips-In1.jpg)

![Det[Table[1/(1. + Abs[i - j]), {i, 1., 150.}, {j, 1., 150.}]] // AbsoluteTiming Det[Table[1/(1. + Abs[i - j]), {i, 1., 150.}, {j, 1., 150.}]] // AbsoluteTiming](http://blog.wolfram.com/data/uploads/2011/12/10Tips-In2.jpg)
More »