英文:
How does sympy handle exponents to the 0.5 power?
问题
((gamma-(gamma**2-omega**2)**0.5)*(gamma+(gamma**2-omega**2)**0.5)).simplify()
输出为:
gamma^2 - (gamma^2 - omega^2)^{1.0} $
然而,我预期的结果是 omega^2。我知道在 sympy 文档中,它警告要小心浮点数,但我以为整数和2的分数次幂(可以精确表示)是可以的。
以下代码正确地得到了 omega^2:
((gamma-(gamma**2-omega**2)**sym.Rational(1,2))*(gamma+(gamma**2-omega**2)**sym.Rational(1,2))).simplify()
为什么第一个代码没有得到预期的结果?
英文:
((gamma-(gamma**2-omega**2)**0.5)*(gamma+(gamma**2-omega**2)**0.5)).simplify()
The output is:
gamma^2 - (gamma^2 -omega^2)^{1.0} $
However, I expected the result to be omega^2. I know in the sympy docs, it warns about being careful with floating point numbers, but I was under the impression that integers and also fractional powers of 2 (which can be represented exactly) were fine.
The following code correctly reproduces omega^2:
((gamma-(gamma**2-omega**2)**sym.Rational(1,2))*(gamma+(gamma**2-omega**2)**sym.Rational(1,2))).simplify()
Why does the first code not produce the expected result?
答案1
得分: 6
SymPy认为精确和非精确数字之间存在区别。在这种情况下,诸如0.5
和1.0
之类的浮点数被认为是非精确的,因此x**1.0
是否真的等于x
或等于稍微不同的值,比如x**1.00000000000000000000001
,这并不清楚。这是因为浮点数通常来自浮点计算,可能存在舍入误差。在你的例子中,结果是:
In [5]: from sympy import *
In [6]: gamma, omega = symbols('gamma, omega')
In [7]: e = ((gamma-(gamma**2-omega**2)**0.5)*(gamma+(gamma**2-omega**2)**0.5)).simplify()
In [8]: e
Out[8]:
1.0
2 ⎛ 2 2⎞
γ - ⎝γ - ω ⎠
如果你想告诉SymPy将1.0
视为精确的1
,那么你可以使用SymPy的nsimplify
函数:
In [9]: nsimplify(e)
Out[9]:
2
ω
英文:
SymPy considers that there is a distinction between exact and inexact numbers. In this context floats like 0.5
and 1.0
are considered to be inexact and therefore it is not clear that x**1.0
is really equal to x
or equal to something slightly different like say x**1.00000000000000000000001
. That is because floats usually arise from floating point calculations which can have rounding errors. In your example the result is:
In [5]: from sympy import *
In [6]: gamma, omega = symbols('gamma, omega')
In [7]: e = ((gamma-(gamma**2-omega**2)**0.5)*(gamma+(gamma**2-omega**2)**0.5)).simplify()
In [8]: e
Out[8]:
1.0
2 ⎛ 2 2⎞
γ - ⎝γ - ω ⎠
If you want to tell SymPy that the 1.0
should be treated as an exact 1
then you can use SymPy's nsimplify
function:
In [9]: nsimplify(e)
Out[9]:
2
ω
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论