Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.



Re: Compiling numerical iterations
Posted:
Feb 27, 2013 3:04 AM


On 2/26/13 at 1:11 AM, cornelius.franz@gmx.net (firlefranz) wrote:
>Thanks a lot! To be honest, some of the commands Ray is using, I've >never seen before. I stopped using mathematica before version 5 came >out.
The functions Ray used were available in version 5 and even earlier.
>Coming back to Peters statement of exporting the code from >Mathematica to C. How this can be done starting from my or Ray's >code? There is an automated Ccodegernerator implemented in >Mathematica 9, am I right?
Yes, version 9 has a C code generator. But it may or may not do what you want. If your Mathematica code doesn't use any specialized functions, the C code generator will likely be fine for you. But if you are using specialized Mathematica functions, I suspect the generator won't output C code for them.
>Here is what I come up with. It's running in a reasonable time for >one particle, but for a real statistic ensemble, I have to do it >over 1.000.000 particles for a long time. Optimizing this or >(probably better) exporting it to C would hopefully help a lot.
Your code example makes considerable use of For. Here is something to consider:
In[1]:= n = 100000; sum = 0; Timing[For[k = 0, k <= n, k++, sum += k]; sum]
Out[2]= {0.156014,5000050000}
In[3]:= Timing[Plus @@ Range[n]]
Out[3]= {0.019608,5000050000}
In[4]:= Timing[Total@Range@n]
Out[4]= {0.000449,5000050000}
All of these get the same result for the sum of the first n integers. The first method is easily exported to C and would run much faster after being compiled.
The last code sample uses a specific builtin Mathematica function that may not export nicely to C. But notice it is ~2.5 orders of magnitude faster than the first example using For.
It is very possible to write Mathematica code without using specialized builtin functions that is very portable to C. But that code generally runs much slower than code making use of Mathematica's functional programming paradigm. If you restrict yourself to things that are easily exported to C code, you are really missing out on the true power of Mathematica.



