Get number of digits after the dot in Float

67 views
Skip to first unread message

Paul Royik

unread,
Apr 15, 2021, 4:31:06 PM4/15/21
to sympy
Rational(1,2).evalf(), how do I get 1 here (since 0.5 has 1 digit after the dot)?

Aaron Meurer

unread,
Apr 15, 2021, 6:23:53 PM4/15/21
to sympy
How would you count small numbers like 1.1e-30. Is that 1 digit or 31
digits after the decimal?

Aaron Meurer

On Thu, Apr 15, 2021 at 2:31 PM Paul Royik <distan...@gmail.com> wrote:
>
> Rational(1,2).evalf(), how do I get 1 here (since 0.5 has 1 digit after the dot)?
>
> --
> 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/73ee2ab4-7b12-4938-a1ed-079b3a33fc14n%40googlegroups.com.

Paul Royik

unread,
Apr 16, 2021, 1:56:24 AM4/16/21
to sympy
One digit. Ignore scientific notation.

Aaron Meurer

unread,
Apr 16, 2021, 4:43:22 AM4/16/21
to sympy
In that case, I think the simplest option would be to parse
str(float). Some split() and strip() operations should get you want
you want, or just use a regex.

Aaron Meurer
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/643b8e44-91f1-475f-87ed-f444d584bbaen%40googlegroups.com.

Paul Royik

unread,
Apr 16, 2021, 6:23:17 AM4/16/21
to sympy
How do I make sure that str() doesn't return exponential notation?

Chris Smith

unread,
Apr 16, 2021, 7:57:20 AM4/16/21
to sympy
>>> ndec = lambda x: 0 if '.' not in str(x) else len(str(x).split('.')[1].split('e')[0])
>>> (1, 1.0, 1.23, 1.234e-5, 3e5, 3e33)
(1, 1.0, 1.23, 1.234e-05, 300000.0, 3e+33)
>>> [ndec(i) for i in _]
[0, 1, 2, 3, 1, 0]

(Note that this is not the same thing as the number of significant digits. And if you don't want to count trailing 0s then change `[0]` to `[0].rstrip('0')`)

/c

Paul Royik

unread,
May 11, 2021, 3:27:42 AM5/11/21
to sympy
Thank you!
Reply all
Reply to author
Forward
0 new messages