Is there a fast way to turn floats that are actually integers, to integers in python? For example: 2.0*x+3.1
, I would like to appear as 2*x+3.1
. I could loop through the numbers in the expression and check one by one if x = int(x)
and then replace them (or something like that), but I was wondering if there is a faster, built-in method to do so.
Thank you!
There are a few ways to do this. You could nsimplify(expr, rational=True)
but that will change the 3.1 to 31/10 and then you would have to undo that. The use of replace
does not replace thing which are tested as equal. So the only one-pass solution that I know of is a custom function:
>>> def intify(expr):
... floats = S(expr).atoms(Float)
... ints = [i for i in floats if int(i) == i]
... return expr.xreplace(dict(zip(ints, [int(i) for i in ints])))
...
>>> intify(2.0*x+3.1)
2*x + 3.1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.