pythonsympysymbolic-math

Formatting Nested Square Roots in SymPy


I'm working with sympy to obtain symbolic solutions of equation. This is my code:

import sympy as sp

# Define the symbolic variable
x = sp.symbols('x')

# Define f(x)
f = ((x**2 - 2)**2 - 2)**2 - 2

# Solve the equation f(x) = 0
solutions = sp.solve(f, x)

# Filter only the positive solutions
positive_solutions = [sol for sol in solutions if sol.is_real and sol > 0]

# Print the positive solutions
print("The positive solutions of the equation f(x) = 0 are:")
for sol in positive_solutions:
    print(sol)

I'm using SymPy to solve the equation

[
L_3(x) = \left(\left(x^2 - 2\right)^2 - 2\right)^2 - 2 = 0
]

and I am able to obtain the positive solutions. However, the solutions are returned with nested square roots in a way that makes the inner roots appear on the left side, like this:

sqrt(2 - sqrt(2 - sqrt(2)))
sqrt(2 - sqrt(sqrt(2) + 2))
sqrt(sqrt(2 - sqrt(2)) + 2)
sqrt(sqrt(sqrt(2) + 2) + 2)

I would like the nested square roots to be formatted in a way that they all appear to the right, like this:

sqrt(2 - sqrt(2 - sqrt(2)))
sqrt(2 - sqrt(sqrt(2) + 2))
sqrt(2 + sqrt(2 - sqrt(2))) 
sqrt(2 + sqrt(sqrt(2) + 2))

Is there a way to adjust the output formatting of the solutions so that the nested square roots appear as desired? Any help would be greatly appreciated! Thank you!


Solution

  • Using your current code (applying reverse lexicographic order)

    print("The positive solutions of the equation f(x) = 0 are:")
    for sol in positive_solutions:    
        pretty_print(sol, order='rev-lex')
    

    Resulting

    The positive solutions of the equation f(x) = 0 are:
       ________________
      ╱       ________ 
    ╲╱  2 - ╲╱ 2 - √2  
    
       ________________
      ╱       ________ 
    ╲╱  2 - ╲╱ 2 + √2  
    
       ________________
      ╱       ________ 
    ╲╱  2 + ╲╱ 2 - √2  
    
       ________________
      ╱       ________ 
    ╲╱  2 + ╲╱ 2 + √2  
    

    For further details sorting docs