Re: Adapting function to input type
- To: mathgroup at smc.vnet.net
- Subject: [mg86493] Re: Adapting function to input type
- From: Szabolcs <szhorvat at gmail.com>
- Date: Wed, 12 Mar 2008 05:26:41 -0500 (EST)
- References: <fr7op0$38l$1@smc.vnet.net>
On Mar 12, 6:13=A0am, Mac <mwjdavid... at googlemail.com> wrote: > I'm convinced from what I know of Mathematica that a function can be > programmed to adapt the calculation according to function input > parameter types (scalar or function), but I'm still not sure exactly > how to do it. > > As an example of a current calculation I calculate the probability > curve for an observation "obs", with error "err" and forward model > "forwardmodel" as a function of forest biomass. Here the error > parameter is assumed to be a function (i.e. err[#] in the expression > for pbiomass) > > pbiomass[obs_, err_, forwardmodel_] := Module[{biomass}, > =A0 =A0biomass = Range[1, 1000, 1]; > =A0 =A0Exp[-1*(forwardmodel[#] - obs)^2/(2 err[#]^2)] & /@ biomass > =A0 =A0]; > > I have several possibilities for error models including > > (* a constant error of 4m in height*) > errmod3[b_] := 4; > > (* a relative error expressed as a percentage of the forward model - > here 10% of forward model *) > errmod2[b_] := forwardmodel[b] 0.1; > > Using errmod2 or errmod3 I can call the pbiomass function without > problem using the syntax > > pbiomass[somenumber,errmod2,forwardmodel] > > or > > pbiomass[somenumber,errmod3,forwardmodel] > > Ideally however I would like to have the option of calling pbiomass[] > using a scalar value for err[] as well as a function, for instance in > the case of a 4m height error > > pbiomass[somenumber,4,forwardmodel] > > instead of having to define a separate err function for a constant > value and use this in the call. You could use an anonymous function: pbiomass[somenumber, 4&, forwardmodel] Or you can extend pbiomass to recognize numbers and construct the anonymous function automatically: pbiomass[a_, num_?NumericQ, b_] := pbiomass[a, num &, b] > I'm stumped as to how to implement > this in Mathematica but I'm pretty sure it is possible so I thought I > would pose the question and hopefully learn from the answers. > > Many thanks > > Mac