Search code examples
constantssympysubstitution

Sympy: rewrite an expression in terms of a constant


I am new to Sympy, sorry if this question has an obvious answer.

I would like to rewrite an expression containing nothing but constants (i.e., no symbols (?)) in terms of a constant defined earlier.

from IPython.display import display
import sympy
sympy.init_printing()

r = sympy.S.GoldenRatio - 1
display(r)
display(1 - r)
display(1 - r**2) # equals r

Displays the following expressions:

Result under Jupyter Notebook

But I would like:

r
1 - r
r

(Not sure whether I am actually asking two distinct questions here, one for the first two lines of the result, one for the last line.)


Solution

  • The following kind of gets you there. Printing the expressions with StrPrinter(dict(order='none')).doprint(expr) didn't work well even for unevaluated expressions because of a parenthesizing issue.

    >>> sr= Symbol('(GoldenRatio - 1)')
    >>> r= S.GoldenRatio - 1
    >>> r.subs(r, sr)
    (GoldenRatio - 1)
    >>> (1-r).subs(r, sr)
    1 - (GoldenRatio - 1)
    >>> nsimplify(1-r**2).subs(r, sr)
      1   v5
    - - + --
      2   2
    >>> nsimplify(1-r**2,r.args).subs(r, sr)
    (GoldenRatio - 1)
    

    or

    >>> nsimplify(1-r**2,[S.GoldenRatio]).subs(r, sr)
    (GoldenRatio - 1)