How to make nsimplify give approximate fraction

16 views
Skip to first unread message

Paul Royik

unread,
Aug 10, 2020, 3:56:36 PM8/10/20
to sympy
nsimplify((Integer(149)/25).evalf()) outputs 149.25, as expected
nsimplify((Integer(149)/35).evalf()) outputs 149/35, which is not expected as it is repeating decimal.
How to make it perform approximation to given precision: 4257142857142857/10**15 ?

Aaron Meurer

unread,
Aug 10, 2020, 4:04:38 PM8/10/20
to sympy
I'm not sure if you can get that with nsimplify(). I tried playing
with the tolerance and rational_conversion arguments, but it either
tries to be smart and reconstruct the original fraction, or it gives
the exact base-2 fraction represented by the float
(4793116746272885/1125899906842624).

If I understand correctly, you want to take this decimal

>>> (Integer(149)/35).evalf()
4.25714285714286

and re-interpret it as a base-10 rational. You can convert it to a
string and use Rational(), like

>>> Rational(str((Integer(149)/35).evalf()))
212857142857143/50000000000000

To get the version you mentioned, you should use

>>> (Integer(149)/35).evalf(16)
4.257142857142857
>>> Rational(str((Integer(149)/35).evalf(16)))
4257142857142857/1000000000000000

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/facbc559-651d-4ff2-a1e0-4ae9194b5ac5o%40googlegroups.com.

Paul Royik

unread,
Aug 11, 2020, 1:46:07 AM8/11/20
to sympy
Thank you. It works.
> To unsubscribe from this group and stop receiving emails from it, send an email to sy...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages