Convert all floats in expression to integers

22 views
Skip to first unread message

Christopher Ahern

unread,
Sep 14, 2015, 3:18:21 PM9/14/15
to sympy
For an expression evalf converts integers to floats.

    z = symbols('z')
    expr = 2*z
    expr.evalf()

This yields 2.0*z. Assuming that the coefficients in the expression are actually integers, is there a way to convert them from floats to integers in SymPy while leaving everything else as is?

Francesco Bonazzi

unread,
Sep 14, 2015, 5:13:08 PM9/14/15
to sympy
Try this one:

n [1]: z = symbols('z')

In [2]: expr = 2*z

In [3]: e2 = expr.evalf()

In [4]: e2
Out[4]: 2.0z

In [5]: def exact_float_to_int(x):
   
...:     if isinstance(x, (float, Float)):
   
...:         return Integer(x)
   
...:     return x
   
...:

In [6]: from sympy.strategies.traverse import bottom_up

In [7]: bottom_up(exact_float_to_int)(e2)
Out[7]: 2z


Explanation: SymPy expressions are trees (data structures), bottom_up applies the defined function from the bottom nodes of the expression tree up to the trunk.

Francesco Bonazzi

unread,
Sep 14, 2015, 5:21:20 PM9/14/15
to sympy
A more compact form:

bottom_up(lambda x: Integer(x) if isinstance(x, (float, Float)) else x)(expression)
Reply all
Reply to author
Forward
0 new messages