12

I have an expression that I think could be simplified somewhat and for some reason sympy is not performing what I think are simple simplifications. My code with the example is as follows:

# 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)

I have placed the code above for cut and paste pleasures... The graphical output from iPython is as follows:

enter image description here

I would have expected the final result to be the following:

enter image description here

I thought that based on how I defined the variables the simplifications would have happened, at least the sqrt((R+d)**2)... What am I doing wrong?

Justace Clutter
  • 2,097
  • 3
  • 18
  • 31
  • I specified that when I created the variables (Positive = True, Real = True). At least I thought that is what I was doing when I added those options... – Justace Clutter Dec 19 '14 at 04:29

2 Answers2

21

Try real = True and positive = True (lower case):

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))

Output:

d/c
Evgeny Bobkin
  • 4,092
  • 2
  • 17
  • 21
ErikR
  • 51,541
  • 9
  • 73
  • 124
3

To expand on @user5402's answer, SymPy only does simplifications that are valid for general complex numbers by default. In particular, sqrt(x**2) = x is not true in general. It is true if x is positive. Setting x as Symbol('x', positive=True) tells SymPy that this is the case.

asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • Do you know why the same thing doesn't work out when using parse_expr? Doing x = symbols('x', positive = True, real = True) and expr = simplify(parse_expr("sqrt(x**2)")) returns "sqrt(x**2)" instead of "x". – JohnDoe122 Mar 05 '20 at 19:27
  • `parse_expr` creates new symbols. If you want it to reuse an `x` that you defined before, you need to use `parse_expr('sqrt(x**2), locals())`. – asmeurer Mar 05 '20 at 22:01