Python floating point concepts

Why -22/10 returns -3 in python. Any pointers to this would be helpful to me.

+3
source share
5 answers

PEP 238 , "Changing the Department Operator," I think explains the problems well. In short: when Python was developed, it took on a truncating value for /between integers, simply because most other programming languages ​​have been running since the first FORTRAN compiler was launched in 1957 (the all-top name of the language and that's it ;-) . (One widespread language that did not accept this meaning, using Pascal /to obtain a floating-point result and divto truncate).

2001 , ( PEP, " , , , " ), // / ( " " ).

,

from __future__ import division

( -Q python ). " " ( ), Python 2.x x " " (.. / int s).

Python 3, , " " (/ int a float).

( Python 3)...:

>>> from fractions import Fraction
>>> Fraction(1/2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/fractions.py", line 100, in __new__
    raise TypeError("argument should be a string "
TypeError: argument should be a string or a Rational instance

/ a float, Fraction ( ). :

>>> Fraction(1, 2)
Fraction(1, 2)
>>> Fraction('1/2')
Fraction(1, 2)

gmpy , mpq s, Python 3 Fraction s...

>>> import gmpy
>>> gmpy.mpq(1/2)
mpq(1,2)

(. 3168 ), gmpy Stern-Brocot, " " (, ).

+5

. . :

>>> -22/10
-3
>>> -22/10.0
-2.2000000000000002

Positive:

>>> 22/10
2
>>> 22/10.0
2.2000000000000002

"" , : ?

+10

Python 2.x( 3.x) , . .

from __future__ import division
print(22/10)

2.2000000000000002

, , .

+5

. -22.0/10 , .

+2

, , , , .

22/10 2: 10 * 2 = 20, , 10 20.

, -22/10. -3. , , , 10 * -3 = -30, , 10 -20.

.

,

+2
source

Source: https://habr.com/ru/post/1726585/


All Articles