sigma
sigma

Reputation: 247

How to keep the fraction in the output without evaluating

I try to find out the Characteristic Polynomial and Eigen values using sympy. But when I print the results in Jupyter notebook all the fractions in the coefficients of the polynomials have been evaluated as float(e.g-0.5x**2+1) but I want $(1/2)x^2+1$). Is there anything to solve this problem. Thank you.

My Code

import sympy as sp
from sympy import *
x, y, z = symbols('x,y,z')
init_printing(use_unicode=False, wrap_line=False)
M = sp.Matrix([[0, -1/2], [1/3, 0]])
x = symbols('x')
p = M.charpoly(x)
p

Output.

Output

Upvotes: 0

Views: 1201

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46859

these are the relevant chages

from fractions import Fraction
M = sp.Matrix([[0, -Fraction(1, 2)], [Fraction(1, 3), 0]])

which yield

PurePoly(x**2 + 1/6, x, domain='QQ')

the point is that 1/3 is immediately converted to the float 0.3333... the way to avoid that is to use fractions.Fraction or (probably better) the sympy version thereof: sympy.Rational.

Upvotes: 3

Related Questions