       Re: Compile a Module

• To: mathgroup at smc.vnet.net
• Subject: [mg83171] Re: Compile a Module
• From: Albert <awnl at arcor.net>
• Date: Tue, 13 Nov 2007 07:01:45 -0500 (EST)
• 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]

This is not how Compile works. The following is syntactically what I
believe you try to achieve:

AlongAwayCompiled = Compile[
{{tip, _Real, 1}, {end, _Real, 1}, {calc, _Real, 1}},
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}
]
]

Anyway, since the function VectorAngle can not be compiled, you need to
either avoid it (you can look at its docpage to get an idea about how
you could replace it) or you tell Compile what kind of result it gives
with a third argument:

AlongAwayCompiled = Compile[{
{tip, _Real, 1}, {end, _Real, 1}, {calc, _Real, 1}
},
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}
],
{{VectorAngle[_, _], _Real}}
]

In:= AlongAwayCompiled[{-1,0},{1,0},{2,1}]

Out= {2.,1.}

This works without error messages but since the compiled function still
has to call back to the regular evaluation for VectorAngle I doubt that
it will be much faster than the uncompiled version...

hth,

albert

```

• Prev by Date: Re: Compile a Module
• Next by Date: Problem with BoxForm`e\$ in MathPlayer conversion
• Previous by thread: Re: Compile a Module
• Next by thread: Re: Compile a Module