Re: Compiled function changes somehow.
- To: mathgroup at smc.vnet.net
- Subject: [mg78587] Re: [mg78568] Compiled function changes somehow.
- From: Carl Woll <carlw at wolfram.com>
- Date: Thu, 5 Jul 2007 03:55:10 -0400 (EDT)
- References: <200707040940.FAA08568@smc.vnet.net>
Nacho wrote:
>Hello.
>
>I have been playing with Compile to accelerate some simple code and I
>have found some differences that I cannot explain.
>
>The standard/compiled code is as follows:
>
>standard[max_] :=
> Table[n/m, {n, 1, max}, {m, 1, max}] // N // Flatten;
>
>compiled =
> Compile[{{max, _Integer}},
> Table[n/m, {n, 1, max}, {m, 1, max}] // N // Flatten];
>
>So I can do the same calculations with both codes:
>
>In[19]:= standardresult = standard[1000]; // Timing
>
>Out[19]= {2.969, Null}
>
>In[20]:= compiledresult = compiled[1000]; // Timing
>
>Out[20]= {0.422, Null}
>
>
>The second is much faster, as expected. But are the results the same?
>Apparently, yes:
>
>In[21]:= standardresult == compiledresult
>
>Out[21]= True
>
>In[22]:= standardresult === compiledresult
>
>Out[22]= True
>
>
>But when I use Union in the lists to count the number of different
>elements, I have this surprise:
>
>Length[Union[standardresult]]
>Length[Union[compiledresult]]
>
>Out[23]= 608383
>Out[24]= 634815
>
>So they are not exactly the same... I think that the correct answer
>comes from the uncompiled version. It is the same if I remove the //N
>so it can be compared symbolically.
>
>Is this behaviour expected? Am I missing something?
>
>Both seem to be Machine Precision, but obviously there are some little
>differences. This happens with V5.2 and V6.0.
>
>Any hint?
>
>Thank you.
>
>
>
The difference is that Compile is converting your integers to reals and
then computing the fractions (this means that the //N is unnecessary in
your Compile code).
One way to see what is going on is to define the following function:
nstandard[max_] := Table[N[n]/N[m], {n, max}, {m, max}] // Flatten
which is essentially what Compile does (Compile does not handle
rationals). Then,
In[174]:= nstandard[1000] // Union // Length
Out[174]= 634815
which is the same result as given by your compiled function, and
In[175]:= compiled[1000] === nstandard[1000]
Out[175]= True
Carl Woll
Wolfram Research
- References:
- Compiled function changes somehow.
- From: Nacho <ncc1701zzz@gmail.com>
- Compiled function changes somehow.