Re: Re: Defining functions using the output of an other function
- To: mathgroup at smc.vnet.net
- Subject: [mg59638] Re: [mg59620] Re: Defining functions using the output of an other function
- From: stephen layland <layland at wolfram.com>
- Date: Mon, 15 Aug 2005 06:50:30 -0400 (EDT)
- References: <ddk892$167$1@smc.vnet.net> <200508140838.EAA12983@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
and thus spake David Bailey [2005.08.14 @ 04:22]:
> Hi,
>
> Of course - Mathematica is nothing if not flexible! First note that you
> need to use == to define an equation for Solve:
>
> Solve[y==x^2,x]
>
> Now we can define a function that uses this:
>
> f[y_]=(x/.Solve[y==x^2,x])[[2]]
>
> There are two points to note:
>
> 1) Solve returns two solutions, and I picked the second one.
>
> 2) I defined the function using = rather than := so that the rhs was
> evaluated at once.
3) I know this is probably more than the user is asking for, but just as
a general caution... be careful using Set in cases like this as it
will _only_ work as you are expecting if y is not previously defined.
For (an admittedly contrived) example:
In[1]:= y = somevar;
f[y_] = x/.Solve[y==x^2,x]
Out[2]= {-Sqrt[somevar], Sqrt[somevar]}
In[3]:= f[5] == f[6]
Out[3]= True
which is almost certainly not what you want.
Using Set to evaluate immediately is definitely more efficient for
equations with a closed form symbolic solution, but be aware of
potential variable clobbering that might crop up in complicated
sessions (like executing multiple notebooks in the same kernel).
--
/*------------------------------*\
| stephen layland |
| Documentation Programmer |
| http://members.wri.com/layland |
\*------------------------------*/
- References:
- Re: Defining functions using the output of an other function
- From: David Bailey <dave@Remove_Thisdbailey.co.uk>
- Re: Defining functions using the output of an other function