I am expecting achieve function composition. The output for laplace
defined as composition is different to symmetric
This is my tried.
from sympy import Function, Symbol
from sympy.printing import pprint
x = Symbol(name="x", real=True)
h = Symbol(name="h", positive=True)
u = Function("u")
def forward(x):
return (u(x + h) - u(x)) / h
def backward(x):
return (u(x) - u(x - h)) / h
def centered(x):
return (u(x + h) - u(x - h)) / (2 * h)
def symmetric(x):
return (u(x - h) - 2 * u(x) + u(x + h)) / h**2
def compose(f, g):
return lambda x: f(g(x))
laplace = compose(backward, forward)
pprint(forward(x))
pprint(backward(x))
pprint(centered(x))
pprint(symmetric(x))
pprint(laplace(x))
# assert symmetric.equals(laplace().simplify())
-u(x) + u(h + x)
────────────────
h
u(x) - u(-h + x)
────────────────
h
-u(-h + x) + u(h + x)
─────────────────────
2⋅h
-2⋅u(x) + u(-h + x) + u(h + x)
──────────────────────────────
2
h
⎛-u(x) + u(h + x)⎞ ⎛ -u(x) + u(h + x)⎞
u⎜────────────────⎟ - u⎜-h + ────────────────⎟
⎝ h ⎠ ⎝ h ⎠
──────────────────────────────────────────────
h
I asked a while ago something related to composition, since composition is about replacing expressions, but I would like if we can do it in a naive way.
5