Search code examples
pythonpython-3.xsympysquare-rootsimplification

Sympy simplification is broken (square roots)?


I tried this in python shell

>>> from sympy import sqrt
>>> sqrt((-9/10 + 6*sqrt(3)/5)**2 + (6/5 + 9*sqrt(3)/10)**2)
sqrt((-0.9 + 6*sqrt(3)/5)**2 + (1.2 + 9*sqrt(3)/10)**2)

and when type it in google:

Google Calculator

So how do I get numpy to give me a more simpilified result (it won't always be an int so I cant use evalf or N)


Solution

  • There are 2 things missing here:

    1. You need to explicitly tell sympy to simplify the expression if it's something complex.
    2. You should use Rational whenever possible, to avoid numerical inaccuraties of floating point arithmetic

    All in all:

    >>> from sympy import Rational, simplify, sqrt
    >>> simplify(sqrt((-Rational(9, 10) + Rational(6,5)*sqrt(3))**2 + (Rational(6,5) + Rational(9,10)*sqrt(3))**2))
    3