MathGroup Archive 2001

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

Search the Archive

RE: R: Local iterator

  • To: mathgroup at smc.vnet.net
  • Subject: [mg29413] RE: [mg29398] R: Local iterator
  • From: "David Park" <djmp at earthlink.net>
  • Date: Mon, 18 Jun 2001 03:39:12 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

Vincenzo,

f[x_] := Log[x]/x^3

To find the maximum you could use Solve[f'[x]==0,x] and then calculate f[x]
in this particular case. But you are interested in an approximation by using
equal spaced samples. Here is one routine which uses an iterator. It is more
convenient to give the function name, or a pure function and skip having to
name the variable.

funMax2[f_, x1_, x2_, step_] :=
  Module[{fval, x, result = {-Infinity, Null}},
    Do[fval = f[x];
      If[fval > First[result], result = {fval, x}], {x, x1, x2, step}];
    result
    ]

funMax2[f, 1, 3, 0.001]
{0.122626,1.396}

Here is a second routine which works on the lists of x values and function
values.

funMax3[f_, x1_, x2_, step_] :=
  Module[{xvals, fvals, maxval},
    xvals = Range[x1, x2, step];
    fvals = f /@ xvals;
    maxval = Max[fvals];
    {maxval, xvals[[#]][[1]] & /@ Position[fvals, maxval]}
    ]

funMax3[f, 1, 3, 0.001]
{0.122626,{1.396}}

If the maximum occurs at more than one x value, the routine returns all of
them.

funMax3[Sin, 0, 4*Pi, 4*(Pi/2^8)]
{1, {Pi/2, (5*Pi)/2}}

David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/



> From: Vincenzo Vasta [mailto:vvasta at btinternet.com]
To: mathgroup at smc.vnet.net
>
> Given a function y = f[x] I would like to write a function that returns,
> for a given interval and a
> given step, the maximum value of y, and the x that generated this
> value. For
> example:
>
>  In[4]  :=  funMax[ Log[x]/x^3 ,x ,1 ,3 ,0.001 ]
>  Out[4]=  {0.122626, 1.396}
>
> With my very little knowledge of Mathematica I wrote funMax like this:
>
>   Clear[funMax];
>   SetAttributes[funMax, HoldAll];
>   funMax[fun_, v_, x1_, x2_, step_] := Block[
>     {v, maxVal = {0, 0} , fval},
>     For[v = x1, v <= x2, v += step,
>       fval = fun;
>       If [maxVal[[1]] <  fval,
>         maxVal = { fval, v}, 0]
>       ];
>     maxVal
>     ]
>
> This function works and I'm happy with that but I would like to
> know how can
> I write it using an
>  iterator. It is just a curiosity about the language.
>
> Thanks for your help
> Vincenzo
>
>
>
>



  • Prev by Date: RE: Functions with Variables with Indices
  • Next by Date: Re: Java, Graphics Output, MathCanvas
  • Previous by thread: Re: R: Local iterator
  • Next by thread: Roots of a function