2
$\begingroup$

To be completely honest I am a litte lost.

Let us say a variable x is defined as y = 1/x. I have one function

f[x_]:= x^2

which I would like to multiply into another function

g[y_]:= Exp[y] + y^2 + 3 y 

Without having to change all y into x. The way I'd do it is

G[y_]:= f[1/y][Exp[y] + y^2 + 3 y]

Is this a correct approach? Are there smarter ways to do it?

$\endgroup$
  • 2
    $\begingroup$ Use parentheses ((...)) to group expressions, not square brackets ([...]) - those are only for function arguments in Mathematica. Also, why not use f[1/y]*g[y]? $\endgroup$ – Lukas Lang Jan 9 at 17:22
  • $\begingroup$ Yes I can do that. I just wanted to make sure that just putting f[1/y] inside there wouldn't cause any issues. Thank you ! $\endgroup$ – Benjamin Jabl Jan 9 at 20:03
1
$\begingroup$

There are quite a few ways to accomplish what you want to do. Here are some.

f[x_] := x^2
g[y_] := Exp[y] + y^2 + 3 y

The simplest is probably is what Lukes suggested.

fg1[y_] := f[1/y] g[y]

or as pure function

fg2 = f[1/#] g[#] &;

However, in this case, since it is easy to define x as the inverse function of y,

x[y_] := 1/y

Composition ( @* ) can also be used.

fg3[y_] := (f@*x)[y] g[y]

or

fg4 = f@*x@# g@#&;

The last definition is a good example of the Wolfram Language's terse functional style. Some consider it elegant; others consider it obscure.

You can be satisfy yourself that all the definitions represent the same function by evaluating

Show[
  MapThread[
    Plot[#1[t], {t, 0, 10}, PlotStyle -> Directive[AbsoluteThickness[#2], #3]] &, 
    {{fg1, fg2, fg3, fg4}, {17, 11, 7, 2}, {Red, Green, Orange, Black}}],
  ImageSize -> Large]

plot

$\endgroup$
  • 1
    $\begingroup$ You seem to have forgotten a space in before g in the definition of fg4 $\endgroup$ – Lukas Lang Jan 9 at 20:18
  • $\begingroup$ @LukasLang. Good catch. I have made the required edit. $\endgroup$ – m_goldberg Jan 9 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.