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

-- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sympy.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sympy/CAHVvXxTS8%3D5PxvCSpBzspec9aigkUFobPNsxnEatgYJaEJ14EA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to