SymPy's subs
and replace
are similar non-functions of substitution and replacement.
from sympy import symbols, sin, cos, exp, I, sqrt, expand, init_printing
init_printing()
x = symbols('x')
f = sin(x)+sin(x**2)
The following example substitutes cos (x)
for sin (x)
.
f.subs(sin(x), cos(x))
Obviously, in this case, sin (x ** 2)
is not replaced by cos (x ** 2)
.
I don't know if this is the intended specification, but .subs (sin, cos)
replaces sin
with cos
.
f.subs(sin, cos)
However, .subs (sin, sqrt)
does not replace sin
with sqrt
.
f.subs(sin, sqrt)
I'm not sure, but I feel that sympy.core.function.FunctionClass
can be replaced with each other.
for func in [sin, cos, sqrt]:
print(func.__class__)
<class 'sympy.core.function.FunctionClass'>
<class 'sympy.core.function.FunctionClass'>
<class 'function'>
Originally, I think that replace
is the original usage to replace a function with a function.
f.replace(sin, cos)
f.replace(sin, sqrt)
You can use your own function or lambda expression as the argument of replace
.
f.replace(sin, lambda t: cos(t**2)) # sin(□)Cos(□**2)Replace with
Euler's formula
cos2exp = lambda t: (exp(t*I) + exp(-t*I))/2
sin2exp = lambda t: (exp(t*I) - exp(-t*I))/(2*I)
(sin(x)+cos(x)).replace(cos, cos2exp).replace(sin, sin2exp)
By using this, various formulas of trigonometric functions can be proved (confirmed).
alpha, beta = symbols(r'\alpha \beta')
A = sin(alpha+beta)
B = sin(alpha)*cos(beta) + cos(alpha)*sin(beta)
expand(A.replace(sin, sin2exp).replace(cos, cos2exp))
expand(B.replace(sin, sin2exp).replace(cos, cos2exp))
Now, ʻA = B`, that is