MathGroup Archive 2001

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

Search the Archive

Re: R: Local iterator

  • To: mathgroup at smc.vnet.net
  • Subject: [mg29409] Re: [mg29398] R: Local iterator
  • From: BobHanlon at aol.com
  • Date: Mon, 18 Jun 2001 03:39:09 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

In a message dated 2001/6/16 10:56:16 PM, vvasta at btinternet.com writes:

>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.
>

SetAttributes[funMax1, HoldAll];

funMax1[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];

SetAttributes[funMax2, HoldFirst];

funMax2[func_, {x_Symbol, x1_?NumericQ, x2_?NumericQ, xstep_:1}] := 
    Module[{}, 
      Last[Sort[Table[{func, x}, {x, x1, x2, xstep}]]]];

funMax1[Log[x]/x^3, x, 1, 3, 0.001]//Timing

{0.4499999999970896*Second, 
  {0.12262643786818798, 1.3959999999999564}}

funMax2[Log[x]/x^3, {x, 1, 3, 0.001}]//Timing

{0.21666666665987577*Second, 
  {0.12262643786818797, 1.396}}

However, finding the actual maximum is much faster than these estimations

({-#[[1]], x/.#[[2]]}& [FindMinimum[-Log[x]/x^3, {x, 1.5}]])//Timing

{0.01666666667733807*Second, 
  {0.12262648039045491, 1.3956127273029095}}


Bob Hanlon
Chantilly, VA  USA


  • Prev by Date: Nonlinear fit versus FindMinimum
  • Next by Date: RE: Functions with Variables with Indices
  • Previous by thread: R: Local iterator
  • Next by thread: RE: R: Local iterator