Sympy如何处理0.5次方的指数?

huangapple go评论76阅读模式
英文:

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.51.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
ω 

huangapple
  • 本文由 发表于 2023年2月18日 11:50:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定