Mathematica 9 is now available
Student Support Forum
-----
Student Support Forum: 'compiling functions' topicStudent Support Forum > General > Archives > "compiling functions"

Help | Reply To Topic
Author Comment/Response
Tobias
10/16/07 10:59am

Hi,

I'd be really grateful if someone could help me out with the following problem.

Say I want to make a compiled version of a function f. What I typically do is this:

(* Uncompiled function *)
f[x_] := x^2
(* Compiled version: *)
fC = Compile[{x}, f[x] // Evaluate];

Using Evaluate inside Compile like this means that I don't have to rewrite the definition of f, which is very useful if f has a lengthy definition, or makes calls to other functions. However, the problem occurs when you want to compile a function that involves random numbers. For instance, the following code has a problem:

(* Uncompiled function *)
g[x_] := RandomReal[{-1, 1}] x^2
(* Compiled version: *)
gC = Compile[{x}, g[x] // Evaluate];

Now gC[1] will give the same answer on successive evaluations, because RandomReal is evaluated just once when gC is compiled. The intended behaviour, of course, is that gC behaves like g, with a new random number each time.

Any advice on how to work around this problem will be much appreciated!

Tobias

URL: ,
Help | Reply To Topic