Groups
Groups
Sign in
Groups
Groups
sympy
Conversations
About
Send feedback
Help
Handling of floats in sympy
24 views
Skip to first unread message
Oscar Benjamin
unread,
Mar 1, 2016, 11:05:00 AM
3/1/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to sympy
I find sympy's handling of Python floats strange and unintuitive.
In [3]: sympify(0.1)
Out[3]: 0.100000000000000
In [4]: sympify(0.1) == S(1)/S(10)
Out[4]: True
In [5]: 0.1 == S(1)/S(10)
Out[5]: True
In [6]: from decimal import Decimal
In [7]: 0.1 == Decimal('0.1')
Out[7]: False
In [8]: 1.0 == Decimal('1.0')
Out[8]: True
In [9]: a = Decimal('0.1')
In [10]: a
Out[10]: Decimal('0.1')
In [11]: b = sympify(0.1)
In [12]: c = 0.1
In [13]: a == b == c
Out[13]: True
In [14]: a == c
Out[14]: False
The true value of c is:
In [18]: Decimal(c)
Out[18]: Decimal('0.1000000000000000055511151231257827021181583404541015625')
In [19]: from fractions import Fraction
In [20]: Fraction(c)
Out[20]: Fraction(3602879701896397, 36028797018963968)
But sympy seems to just convert it to 15 decimal digits without any
indication that the conversion was inexact.
What's the rationale for the inexactness here? How do I convert a
float to a sympy object with the exact same value?
It looks as if sympy converts Python Decimals using __float__ e.g.:
In [31]: a = Decimal(0.1)
In [32]: a
Out[32]: Decimal('0.1000000000000000055511151231257827021181583404541015625')
In [33]: S(a)
Out[33]: 0.100000000000000
OTOH Fraction can do it:
In [34]: Fraction(0.1)
Out[34]: Fraction(3602879701896397, 36028797018963968)
In [35]: S(Fraction(0.1))
Out[35]:
3602879701896397
─────────────────
36028797018963968
--
Oscar
Reply all
Reply to author
Forward
0 new messages