MathGroup Archive 2013

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Compiling numerical iterations

  • To: mathgroup at
  • Subject: [mg129935] Re: Compiling numerical iterations
  • From: Bill Rowe <readnews at>
  • Date: Wed, 27 Feb 2013 03:04:57 -0500 (EST)
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:
  • Delivered-to:

On 2/26/13 at 1:11 AM, cornelius.franz at (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

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 C-code-gernerator 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 built-in 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 built-in 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.

  • Prev by Date: Re: Mathematica and Lisp
  • Next by Date: Re: Real and Imaginary Parts of complex functions
  • Previous by thread: Re: Compiling numerical iterations
  • Next by thread: Re: Compiling numerical iterations