Search code examples
pythonsympysymbolic-math

Find a simple representation for a number with SymPy


I am struggling to simplify the following term with sympy

(latex) $\sqrt3{8+3\sqrt{21}}+\sqrt3{8-3\sqrt{21}}$

from sympy import (
    init_printing,
    sqrt,
    cbrt,
    nsimplify,
    simplify,
)

init_printing(use_unicode=True)

value_plus = cbrt(8 + 3 * sqrt(21))
value_minus = cbrt(8 - 3 * sqrt(21))

value_both = value_plus + value_minus

Here, I have separeted the expression in two parts value_plus and value_minus, respectively.

For the first part, I get a desired result

nsimplify(value_plus)

which is $1/2+\sqrt{21}/2$ as can be seen in wolfram alpha.

However, for the second part intead of a desired result ($1/2-\sqrt{21}/2$) as can be seen in wolfram aplha as well, under alternate form

nsimplify(value_minus)

I end up with a complex representation, which is also correct, but not exactly what I want to get.

And thus, I do not get the expected result, which is 1.

value_both = value_plus + value_minus

as can be seen on the screenshot. So my questions are,

  1. how to force other representations of a number?
  2. how to restrict the representation to real numbers only?

Screenshot of a jupiter notebook


Solution

  • Instead of cbrt you can use real_root:

    value_plus = real_root(8 + 3 * sqrt(21), 3)
    value_minus = real_root(8 - 3 * sqrt(21), 3)
    
    value_both = value_plus + value_minus
    
    print(nsimplify(value_plus))
    print(nsimplify(value_minus))
    print(nsimplify(value_both))
    

    Output will be:

    1/2 + sqrt(21)/2
    1/2 - sqrt(21)/2
    1