How do I replace floats with rationals in a sympy expression?
Use nsimplify
:
>>> print(nsimplify(sqrt(pi)*(0.333333333333333*a + 0.333333333333333*b - 2.66666666666667*c**2)))
sqrt(pi)*(a/3 + b/3 - 8*c**2/3)
After a bit of fiddling, I think I have found a way to do it, but I am not sure that it will cover all the corner cases. At any rate here it is. Any suggestions for improvement?
import sympy
def rationalize_coeffs(expr):
for i in expr.atoms(sympy.Float):
r = sympy.Rational(str(i)).limit_denominator(1000)
expr = expr.subs(i, r)
return expr
if __name__=='__main__':
# given a sympy expression expr
x,y,z = sympy.symbols('x y z')
# expr_orig = 2/57.*x + 3./4.*y + 3./4.*z
expr = 0.0350877192982456*x + 0.75*y + 0.75*z
print rationalize_coeffs(expr)