Re: Derivatives D[ ] as Functions inside Tables; Need Help!
- To: mathgroup at smc.vnet.net
- Subject: [mg13203] Re: Derivatives D[ ] as Functions inside Tables; Need Help!
- From: "Allan Hayes" <hay at haystack.demon.cc.uk>
- Date: Mon, 13 Jul 1998 07:42:52 -0400
- References: <6nsil0$f32@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
AES wrote in message <6nsil0$f32 at smc.vnet.net>...
>I'm trying to define a function f1[a,x] and its derivative f2[a,x],
>where from my point of view x is the independent variable and "a" is
>a parameter I'll change on different runs. So I write, as a simple
>example:
>
> Remove["Global`*"]
>
> f1[a_,x_] :=a Cos[x] + a^2 Sin[x]
>
> f1[a,x]
>
> f2[a_,x_] := D[f1[a,x],x]
>
> f2[a,x]
>
> a=2
>
> f1[a,x]
>
> f2[a,x]
>
> Table[{x, f1[a,x], f2[a.x]} // N, {x,0,4}] // TableForm
>
>and everything looks fine -- except the function f2[a,x] will not
>evaluate inside the Table[ ]. I don't understand this -- help in
>understanding will be much appreciated.
>
> siegman at ee.stanford.edu
>
Clear["Global`*"]
f1[a_,x_] :=a Cos[x] + a^2 Sin[x];
f2[a_,x_] := D[f1[a,x],x];
The main problem is that Table finds the f2[x,y] for x = 1, say, by a
process like
x=1;
f2[a,x]
General::ivar: 1 is not a valid variable.
2
D[a Cos[1] + a Sin[1], 1]
We need to evaluate the symbolic f2[a,x] before x takes the value 1
x=1;
Block[{x},f2[a,x]]
2
a Cos[1] - a Sin[1]
With the example given, the pre-evaluation can be achieved in several
ways:
a=2;
(1)
Table[Block[{x},{x, f1[a,x], f2[a,x]}]//N , {x,0,4}] // TableForm
0 2. 4.
1. 4.44649 0.478267
2. 2.8049 -3.48318
3. -1.4155 -4.24221
4. -4.3345 -1.10097
(2)
x=. (* essential*)
Table[Evaluate[{x, f1[a,x], f2[a,x]}] , {x,0,4}]//N // TableForm
0 2. 4.
1. 4.44649 0.478267
2. 2.8049 -3.48318
3. -1.4155 -4.24221
4. -4.3345 -1.10097
(3)
Make the definitions of f1 and f2 immediate, so that the differention is
done before we construct the Table expression - this is the most
efficient way.
Clear["Global`*"]
f1[a_,x_] =a Cos[x] + a^2 Sin[x];
f2[a_,x_] = D[f1[a,x],x];
a=2;
Table[{x, f1[a,x], f2[a,x]} // N, {x,0,4}] // TableForm
0 2. 4.
1. 4.44649 0.478267
2. 2.8049 -3.48318
3. -1.4155 -4.24221
4. -4.3345 -1.10097
------------------------------------------------------------- Allan
Hayes
Training and Consulting
Leicester UK
http://www.haystack.demon.co.uk
hay at haystack.demon.co.uk
voice: +44 (0)116 271 4198
fax: +44(0)116 271 8642