[Python] Making solveset solutions rational in sympy

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to solve a cubic with a parameter r, for x. The cubic is the awful expression

    poly = b*(-(10 + x)*b - 10*b) - ((8/3) + x)*((10+x)*(1+x) - 10)


    where

    b = sp.sqrt((8/3)*(1 - a))


    which factors out to x^3 + (41/3)x^2 + (8/3)(a + 10)x + (160/3)(a - 1).

    SymPy's solveset() gives a solution, but it is really long mostly due to the large mass of repeated fractions in the answer. I'd like to do something like Rational(solution) to make the solution nicer, but it doesn't work.

    Here's my code and the error:

    import sympy as sp
    from sympy import Eq, solveset, Rational
    from sympy.abc import x, a, b

    poly = b*(-(10 + x)*b - 10*b) - ((8/3) + x)*((10+x)*(1+x) - 10)
    polysub = poly.subs(b,sp.sqrt((8/3)*(1 - a)))
    polyeq = Eq(polysub,0)
    solutionset = solveset(polyeq,x)
    Rational(solutionset)


    TypeError: invalid input: {ridiculously long solution}

    Continue reading...

Compartilhe esta Página