Search code examples
sympy

Why sympy cannot correctly determine identity of simple sqrt expressions?


enter image description here

Even if it correctly determine the inequalities of both sides, it cannot determine the identity.

from sympy import *
assert not 2 * sqrt(2 - sqrt(3)) == -sqrt(2) + sqrt(6)
assert 2 * sqrt(2 - sqrt(3)) <= -sqrt(2) + sqrt(6)
assert 2 * sqrt(2 - sqrt(3)) >= -sqrt(2) + sqrt(6)

assert not 2 * sqrt(2 - sqrt(3)) == sqrt(8 - 4 * sqrt(3))
assert 2 * sqrt(2 - sqrt(3)) <= sqrt(8 - 4 * sqrt(3))
assert 2 * sqrt(2 - sqrt(3)) >= sqrt(8 - 4 * sqrt(3))

Solution

  • The reason is, as commented by @OscarBenjamin, "a==b tests structural equality not mathematical equality."

    The equality operator (==) tests whether expressions have identical form, not whether they are mathematically equivalent.

    https://github.com/sympy/sympy/wiki/Faq#why-does-sympy-say-that-two-equal-expressions-are-unequal

    Double equals signs (==) are used to test equality. However, this tests expressions exactly, not symbolically.

    https://docs.sympy.org/latest/explanation/gotchas.html#double-equals-signs

    Except to use simplify(lhs - rhs) and check if the expression reduces to 0, Eq(lhs, rhs) can be used.

    from sympy import *
    assert Eq(2 * sqrt(2 - sqrt(3)), -sqrt(2) + sqrt(6))
    

    This class is not the same as the == operator. The == operator tests for exact structural equality between two expressions; this class compares expressions mathematically.

    https://docs.sympy.org/latest/modules/core.html#sympy.core.relational.Equality

    See also: https://docs.sympy.org/latest/tutorials/intro-tutorial/gotchas.html#equals-signs

    P.S. .equals tests if two expressions are equal by evaluating them numerically at random points.