MathGroup Archive 2010

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

Search the Archive

Re: Multiline functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg112768] Re: Multiline functions
  • From: Raffy <adraffy at gmail.com>
  • Date: Thu, 30 Sep 2010 04:49:30 -0400 (EDT)
  • References: <i7uses$ram$1@smc.vnet.net>

On Sep 29, 1:13 am, Sam Takoy <sam.ta... at yahoo.com> wrote:
> Hi,
>
> I'm not sure if I'm approaching functions that require several lines
> properly. Here's my approach to solving Laplace's equation on the unit
> circle with Dirichlet boundary conditions. (Construct partial Fourier
> series, multiply each term by r^n and sum.) Something about my code
> seems terribly awkward. I'm looking for comments on how to improve it.
> (Just the code. I know that mathematically there may be better ways.)
>
> Thanks in advance,
>
> Sam
>
> FourierCoefficients[f_, order_] := (
>    out = {1/(2 Pi) Integrate[f[a], {a, -Pi, Pi}]};
>    For[n = 1, n < order, n = n + 1,
>     out = Append[
>       out, {1/Pi Integrate[f[a] Cos[n a], {a, -Pi, Pi}],
>        1/Pi Integrate[f[a] Sin[n a], {a, -Pi, Pi}]}]];
>    out)
>
> LaplaceOnUnitCircle[phi_, order_] := (
>     f[r_, alpha_] = (
>       fc = FourierCoefficients[phi, order];
>       sum = fc[[1]];
>       For[n = 1, n < order, n = n + 1,
>        sum =
>          sum + r^n (fc[[n + 1]][[1]] Cos[n alpha] +
>              fc[[n + 1]][[2]] Sin[n alpha]);
>        ];
>       sum);
>     f
>     );
> LaplaceOnUnitCircle[Cos, 5][r, \[Alpha]]
>
> Answer: r Cos[\[Alpha]] - correct.

ClearAll[LaplaceOnUnitCircle];
LaplaceOnUnitCircle[phi_, order_Integer] := With[{
    off = Integrate[phi[a], {a, -Pi, Pi}]/(2 Pi),
    cos = Table[Integrate[phi[a]*Cos[n*a]/Pi, {a, -Pi, Pi}], {n,
order}],
    sin = Table[Integrate[phi[a]*Sin[n*a]/Pi, {a, -Pi, Pi}], {n,
order}]
  },
  Function[{r, a}, off + Sum[r^n*(cos[[n]]*Cos[n*a] +
sin[[n]]*Sin[n*a]), {n, order}]]
];

You'll notice that LaplaceOnUnitCircle[Cos, 5] returns a function that
already has some of the problem evaluated.

Also, this function isn't bound to any global symbol (like f in your
example), which means you can do:
f1 = LaplaceOnUnitCircle[Cos, 5];
f2 = LaplaceOnUnitCircle[Cos, 10];

With is perfect for injecting evaluated results into an unevaluated/
held expression.


  • Prev by Date: Re: Test for dialog existence
  • Next by Date: Re: Mathematica calculates RSquared wrongly?
  • Previous by thread: Re: Multiline functions
  • Next by thread: Re: Defining a function using common notation for absolutevalue (not Abs[x])