TransWikia.com

Redefining the output of a function

Mathematica Asked by SciJewel on April 11, 2021

ftn1 = Sin[s]^2 + 3 t^2 + u^5

3 t^2 + u^5 + sin[s]^2

ftn2[s_, t_, u_] := ftn1

ftn2[2, 1, 2]

3 t^2 + u^5 + Sin[s]^2

Hi there,
In the above code, would somebody like to comment on how to redefine the output of ftn1 in the form ftn2[…] above. This is just a simple example, oftentimes there is a complicated output of ftn1 and one has to copy and paste for ftn2[….]. That’s quite cumbersome, though works well. I am wondering how to directly define ftn2 in terms of the output of ftn1 above so that to avoid copy and paste and also ftn2 works fine. As it can be seen from above "ftn2[2, 1, 2]" fails to work. Thanks!

2 Answers

ftn1 = Sin[s]^2 + 3 t^2 + u^5
ftn2[s_, t_, u_] = ftn1
a=ftn2[2, 1, 2]
N[a]

35 + Sin[2]^2

35.8268

If you prefer to used := then

ftn1 = Sin[s]^2 + 3 t^2 + u^5
ftn2[s_, t_, u_] := Evaluate[ftn1]

Answered by Sumit on April 11, 2021

Your function is defined as,

ftn1 = Sin[s]^2 + 3 t^2 + u^5

3 t^2 + u^5 + Sin[s]^2

If you use ReplaceAll (/.) on ftn1,

ftn1 /. {s -> 2, t -> 1, u -> 2}

35 + Sin[2]^2

You can use N[] to numerically evaluate it,

N[ftn1 /. {s -> 2, t -> 1, u -> 2}]

35.8268

With this knowledge, define ftn2 as ftn2[s1_, t1_, u1_], where s1, t1 and u1 are placeholders for s, t and u respectively. Now we "replace all" variables so that ftn1 is evaluated inside the definition of ftn2 (Techinically, by using :=, fnt1 is not evaluated inside the definition, it is evaluated in the function call of the fnt2 function. We use placeholders so that variables inside ftn2 is clearly separated from the internal variables in ftn1:

ftn2[s1_, t1_, u1_] := ftn1 /. {s -> s1, t -> t1, u -> u1}
ftn2[2, 1, 2]

35 + Sin[2]^2

Suppose now, this is not enough and you need the numerical value, you can use N[] in the definition of the function,

ftn3[s1_, t1_, u1_] := N[ftn1 /. {s -> s1, t -> t1, u -> u1}]
ftn3[2, 1, 2]

35.8268

This should solve your problem!

Answered by Kishore S Shenoy on April 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP