Home > Back-end >  How to convert the co-efficients in these inequalities from float to int in Sympy?
How to convert the co-efficients in these inequalities from float to int in Sympy?

Time:11-17

I have the following expressions -

x > 4.5
2x   y == 4.5

I would like to get rid of the floating point numbers in the coefficients and convert them into integers. How can I do this using Sympy? (or any other python library for that matter). I have been racking my brains for hours now.

BTW, the expected output should be -

2x > 9
4x   2y == 9

Thanks in Advance!

CodePudding user response:

You can use nsimplify() on the relation and multiply both sides by the denominator of the RHS, like the following.

from sympy import nsimplify, Rel
from sympy.abc import x

r0 = x > 4.5

r = nsimplify(r0)
q = r.rhs.q
r = Rel(r.lhs * q, r.rhs * q, r.rel_op)

print([r0, r])

This outputs

[x > 4.5, 2*x > 9]

CodePudding user response:

If you want to clear all denominators (even those that may be symbolic) then this might be a robust way to do so:

def clear_relden(r):
    from sympy.core.relational import Relational
    from sympy import Piecewise
    assert isinstance(r, Relational)
    n, d = zip(*[i.as_numer_denom() for i in r.args])
    l = lcm(*d)
    args = [n[i]*l/d[i] for i in range(2)]
    return Piecewise(
        (r.func(*args), l>0),
        (r.reversed.func(*args), l<0))

For example,

enter image description here

If you have floats, then pass nsimplify(r, rational=True).

  • Related