MathGroup Archive 2007

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

Search the Archive

Re: Compile a Module

  • To: mathgroup at smc.vnet.net
  • Subject: [mg83197] Re: Compile a Module
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Wed, 14 Nov 2007 04:54:07 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <fhbnuc$r4s$1@smc.vnet.net>

JOHN ERB wrote:

> Can the following module be compiled?
>   It needs to be used 10^4 times in my program.
>   It is used to calculate the distance parallel and perpendicular
>   to the midpoint of  2D line segment with reference to a point of interest (calc).
>    
>   AlongAway[{tip_,end_,calc_}]:=Module[{mid,r,theta,along,away},
> mid=(tip+end)/2;
> r=Sqrt[Dot[calc-mid,calc-mid]];
> theta=VectorAngle[calc-mid,end-mid];
> along=r Cos[theta];
> away=r Sin[theta];
> {along,away}]
>    
>   AlongAway[{{-1, 0}, {1, 0}, {2, 1}}]
> (* answer is {2,1} *)
>    
>   (* the code below does not seem to work *)
>   cAlongAway=Compile[{{tip,_Real},{end,_Real},{calc,_Real}},AlongAway]

John,

I have made the following modifications to your code to get it 
compilable and to be sure it runs the compiled version when fed with 
floating-point-number arguments.

The main argument of the function is declared as a tensor of real 
numbers of rank two (i.e. a real matrix).

The arguments tip, end , and calc, are set up within the Module construct.

Finally, we tell Mathematica that, in our case, the built-in function 
*VectorAngle* will always return a floating-point number (*VectorAngle 
can return infinite, arbitrary, or machine-size precision numbers 
depending on its arguments).

In[1]:= cAlongAway =
   Compile[{{m, _Real, 2}},
    Module[{mid, r, theta, along, away, tip = m[[1]], end = m[[2]],
      calc = m[[3]]},
     mid = (tip + end)/2;
     r = Sqrt[Dot[calc - mid, calc - mid]];
     theta = VectorAngle[calc - mid, end - mid];
     along = r Cos[theta];
     away = r Sin[theta];
     {along, away}], {{VectorAngle[_, _], _Real}}];

cAlongAway[{{-1., 0.}, {1., 0.}, {2., 1.}}]

Out[2]= {2., 1.}

HTH,
-- 
Jean-Marc


  • Prev by Date: Re: Can't abort a loop with Print inside (V6)
  • Next by Date: Re: Question about RandomInteger
  • Previous by thread: Re: Compile a Module
  • Next by thread: Huge font size for text