Sympy无法化简正弦欧拉公式?为何结果不为零?余弦可正常化简
Great question! Let's break down why this happens and how to fix it.
First, the core issue here is that SymPy's default simplify() function uses a general-purpose set of rules, and it doesn't always prioritize converting complex exponential expressions with 1/I terms into into trigonometric functions. Here's the breakdown:
Why Cosine Works But Sine Doesn't
The Euler formula for cosine is (e^(ix) + e^(-ix))/2—this expression doesn't involve a reciprocal of the imaginary unit I, so SymPy's default simplify logic easily recognizes it as cos(x).
For sine, though, the formula is (e^(ix) - e^(-ix))/(2i), which is equivalent to -i*(e^(ix)-e^(-ix))/2. The 1/I term here is a small but crucial detail that the default simplify() doesn't automatically handle in this context, so it fails to reduce expr - sin(x) to zero.
Fixes to Get the Expected Zero Result
You have a few straightforward ways to make SymPy recognize the equivalence:
1. Use trigsimp() (Trigonometry-Specific Simplification)
This function is designed explicitly to handle conversions between trigonometric functions and complex exponentials. Replace simplify() with trigsimp():
from sympy import * x = Symbol("x") expr = (1/(2*I)) * (E**(I*x) - E**(-I*x)) print(trigsimp(expr - sin(x))) # Output: 0
2. Expand the Complex Expression with expand_complex()
This function expands complex terms and simplifies them, which will resolve the 1/I term and match it to sin(x):
print(expand_complex(expr - sin(x))) # Output: 0
3. Manually Simplify the 1/(2*I) Term First
Since 1/I = -I, you can rewrite your expression to avoid the reciprocal of I upfront. SymPy's default simplify() will then work as expected:
expr_simplified = (-I/2) * (E**(I*x) - E**(-I*x)) print(simplify(expr_simplified - sin(x))) # Output: 0
The key takeaway is that while simplify() is great for general cases, using specialized functions like trigsimp() or expand_complex() gives you better control when working with trigonometric and complex exponential conversions.
内容的提问来源于stack exchange,提问作者user9730851

