I have defined a function F by $F(x)=(f(x)+h)/g(x)$ where $f, g$ are functions and $h$ a variable.
Suppose that I write $f(x)+h$, how can i ask to sagemath to use F in the result: $F(x)*g(x)$
Thanks
This challenge resists a bit and requires perseverance.
Setting: three functions, one variable, one relation.
sage: f = function('f')
sage: g = function('g')
sage: F = function('F')
sage: h = SR.var('h')
sage: relation = F(x) == (f(x) + h)*g(x)
Warm-up: substituting a subexpression by a chosen replacement in an expression works:
sage: a = (f(x) + h)*g(x)
sage: a
(h + f(x))*g(x)
sage: a.subs({f(x) + h: F(x)})
F(x)*g(x)
Sage will however not go out of its lengths and rearrange things to force a substitution we have in mind but don't describe precisely:
sage: b = f(x) + h
sage: b
h + f(x)
sage: b.subs({(f(x) + h)/g(x): F(x)})
h + f(x)
There just was no actual occurrence of the given subexpression to substitute, so nothing happened.
If we tell it exactly what to substitute, it will:
sage: b.subs({f(x) + h: F(x)*g(x)})
F(x)*g(x)
If we are willing to prepare the ground "by hand", we can divide by g(x) to make the desired subexpression appear, remultiply immediately to cancel out the division, but hold the multiplication so the cancellation does not actually get simplified, and then substitute:
sage: bb = (b / g(x)).mul(g(x), hold=True)
sage: bb
((h + f(x))/g(x))*g(x)
sage: bb.subs({(f(x) + h)/g(x): F(x)})
F(x)*g(x)
Now that we are warmed up, let us restate our goal: get rid of
any occurrence of f(x) in an expression, applying appropriate
substitutions, derived from the relation in the question.
Recall the relation that we want to use for replacements.
sage: relation = F(x) == (f(x) + h)*g(x)
Introduce an auxiliary variable, say z, and substitute it
for the expression to remove in the relation, and solve
to get our replacement dictionary:
sage: z = SR.var('z')
sage: fz = {f(x): z}
sage: rep = solve(relation.subs(fz), z, solution_dict=True)
sage: rep
[{z: -(h*g(x) - F(x))/g(x)}]
The dictionary came in a list, let's unwrap it out of that list.
sage: rep = rep[0]
sage: rep
{z: -(h*g(x) - F(x))/g(x)}
Now we can use that to substitute, first replacing f(x) by z,
then z by the result of solving for z in the modified relation:
sage: b
h + f(x)
sage: b.subs(fz).subs(rep)
h - (h*g(x) - F(x))/g(x)
Almost there... try simplifying...
sage: b.subs(fz).subs(rep).simplify()
h - (h*g(x) - F(x))/g(x)
Didn't work... try harder...
sage: b.subs(fz).subs(rep).simplify_full()
F(x)/g(x)
We did it!
F(x)by your formula. Because in principle,f(x)+hreally isn't the same -g(x)=0would causeF*gto not be in its domain. But of course because it's hard to find things that are missing anyway. – kcrisman Dec 14 '17 at 20:06