Interface promise of conversion to float

36 views
Skip to first unread message

Damien Desfontaines

unread,
Dec 2, 2021, 1:23:31 PM12/2/21
to sympy
Hi all,

This feels like a very simple problem, but I couldn't find a clear answer in the documentation. I have a sympy number x and I would like to round it to the nearest float. Suppose I simply use float(x), and that the true value of x is between two successive floats a and b.
- If x is slightly closer to a than b, is sympy guaranteed to round to a? Same question if x is slightly closer to b.
- If x is exactly equal to (a+b)/2, will float(x) round it up or down?
- Are there situations where sympy can't be sure whether to round up or down? What happens then? Is there a way to detect when that happens?

Thanks a ton in advance,

Damien

Aaron Meurer

unread,
Dec 2, 2021, 4:55:36 PM12/2/21
to sy...@googlegroups.com
I believe it uses round-to-even, but note that the rounding is done in
base-2, not base-10. If you're worried about the rounding, you can
evaluate the number to more digits using evalf() to see exactly how it
rounded.

If you want to use a specific base-10 rounding mode, I believe
currently the only way is to get a float with sufficient digits from
evalf() then use the methods in the standard library decimal module.

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/aa33ca28-6a88-44f8-b872-9fa6717eb22cn%40googlegroups.com.

Damien Desfontaines

unread,
Dec 14, 2021, 12:56:34 PM12/14/21
to sympy
Thanks! Round-to-even in base-2 is perfect for my use case. Is there a document or a piece of source code somewhere I could use as a reference for that fact?

I can't use evalf() with a fixed number of digits because I don't know in advance how many digits I need: if the number is close to 0, then I might need a ton of precision (the exponent can be -126, possibly even less if subnormals are supported) than if the number is large (e.g. if the number is closed to 1, you only need a precision of 2^-53).

Aaron Meurer

unread,
Dec 14, 2021, 3:56:36 PM12/14/21
to sy...@googlegroups.com
I'm not sure if the SymPy docs mention it (you'd have to search). The
mpmath docs might, which is what SymPy is using under the hood to do
the rounding.

Aaron Meurer

On Tue, Dec 14, 2021 at 10:56 AM Damien Desfontaines
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/1a416ef3-9670-41ec-b43b-bead64bf8980n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages