Sympy简化与平方根

时间:2014-12-19 03:05:05

标签: python sympy simplify

我有一个表达式,我认为可以在某种程度上简化,并且出于某种原因,同情不表现我认为简单的简化。我的示例代码如下:

# coding: utf-8

# In[1]:

from __future__ import division
from sympy import *
init_printing()

# In[3]:

d, R, c = symbols('d R c', Positive = True, Real = True)
Δt = symbols('\Delta_t', Real = True)

# In[4]:

Δt = (1/c**2)*(-R*c+sqrt(c**2*(R+d)**2))
Δt

# In[5]:

simplify(Δt)

我已将上面的代码放在剪切和粘贴乐趣中......来自iPython的图形输出如下:

enter image description here

我原以为最终结果如下:

enter image description here

我认为根据我如何定义变量,简化会发生,至少sqrt((R + d)** 2)......我做错了什么?

2 个答案:

答案 0 :(得分:7)

尝试real = Truepositive = True(小写):

import sympy as sp

d, R, c = sp.symbols('d R c', positive = True, real = True)
dt = sp.symbols('\Delta_t', real = True)

dt = (1/c**2)*(-R*c+sp.sqrt(c**2*(R+d)**2))

print(sp.simplify(dt))

输出:

d/c

答案 1 :(得分:2)

为了扩展@ user5402的答案,SymPy默认只执行对一般复数有效的简化。特别是sqrt(x**2) = x一般不正确。如果x为正,则确实如此。将x设置为Symbol('x', positive=True)会告诉SymPy这种情况。