MathGroup Archive 2001

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

Search the Archive

Re: Compiling functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg31752] Re: [mg31720] Compiling functions
  • From: Andrzej Kozlowski <andrzej at tuins.ac.jp>
  • Date: Sat, 1 Dec 2001 02:43:58 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

The cause of your problem is that Compile has the attribute HoldAll:

In[1]:=
Attributes[Compile]

Out[1]=
{HoldAll,Protected}


There are several ways to get around it and your other problem (complex 
square root). One way is simply to use your expression directly in 
Compile (without an intermediate variable expr) and specify that all the 
variables are to be considered complex:

In[2]:=
t1=Compile[{{a,_Complex},{b,_Complex},{c,_Complex}},
(-b+Sqrt[b^2-4*a*c])/(2*
             a)];


In[3]:=
t1[1,2,3]

Out[3]=
-1.+1.41421 I

In[4]:=
t1[1,2,-3]//Chop

Out[4]=
1.

(without the Chop you will get a tiny imaginary part).

Another approach is to define expr as a function rather than a variable:
In[5]:=
expr[a_,b_,c_]:=(-b+Sqrt[b^2-4*a*c])/(2*a)

In[6]:=
t2=Compile[{a,b,c},expr[a,b,c],{{expr[___],_Complex}}];

This time a,b and c are taken as real but we use a third argument in 
Compile to specify that expr returns complex values:

In[5]:=
t2[1,2,3]

Out[5]=
-1.+1.41421 I

In[6]:=
t2[1,2,-3]//Chop

Out[6]=
1.

There are a few other variants on this but I think the basic ideas are 
all contained in these two exapmles.

Andrzej Kozlowski
Toyama International University
JAPAN
http://platon.c.u-tokyo.ac.jp/andrzej/

On Thursday, November 29, 2001, at 02:13  PM, Cyril Fischer wrote:

> Hello. I would like to ask you for help with compiling functions.
>
> Let's have
> expr = (-b + Sqrt[b^2 - 4*a*c])/(2*a)
>
> Simple compile does not work for me:
> tf = Compile[{a, b, c}, expr];  tf[1, 2, 3]
>
> in this case the the values are not substitued for symbols.
>
> Such a ugly construction works
> tf = Compile[{a1, b1, c1},
>     Evaluate[expr /. {a -> a1, b -> b1, c -> c1}]]; tf[1, 2, 3]
>
> however it failes to evaluate compiled expression as the sqrt result is
> not real.
>
> 1. How can I compile (assigned) expressions without substitution for
> each parameter?
>
> 2. How can I compile expressions, which (for real input) can give
> complex output?
>
> Thanks, Cyril F.
>
>
>
>



  • Prev by Date: Re: EPS Export, Wrong characters
  • Next by Date: Re: Very difficult axes inversion?? How to???
  • Previous by thread: Re: Compiling functions
  • Next by thread: Path finding in graph theory, Lookig for your help,