[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

On Wed, Aug 29, 2018 at 12:11 AM, Frank Millman <frank at chagford.com> wrote: > Hi all > > I know about this gotcha - > >>>> x = 1.1 + 2.2 >>>> x > > 3.3000000000000003 > > According to the docs, the reason is that "numbers like 1.1 and 2.2 do not > have exact representations in binary floating point." > > So when I do this - > >>>> y = 3.3 >>>> y > > 3.3 > > what exactly is happening? What is 'y' at this point? > > Or if I do this - > >>>> z = (1.1 + 2.2) * 10 / 10 >>>> z > > 3.3 > > What makes it different from the first example? > Here's how you can find out *exactly* what a Python float is: >>> y = 3.3 >>> y.as_integer_ratio() (3715469692580659, 1125899906842624) >>> x = 1.1 + 2.2 >>> x 3.3000000000000003 >>> x.as_integer_ratio() (7430939385161319, 2251799813685248) >>> z = (1.1 + 2.2) * 10 / 10 >>> z 3.3 >>> z.as_integer_ratio() (3715469692580659, 1125899906842624) >>> (1.1).as_integer_ratio() (2476979795053773, 2251799813685248) >>> (2.2).as_integer_ratio() (2476979795053773, 1125899906842624) The value of y is exactly (3715469692580659 / 1125899906842624) which is 3.299999999999999822364316060. But x is a teeny bit higher. You can explore these with the help of decimal.Decimal, too. The values given by as_integer_ratio() are possibly more interesting in hex than in decimal, with values like these.

- Prev by Date:
**Question about floating point** - Next by Date:
**Question about floating point** - Previous by thread:
**Question about floating point** - Next by thread:
**Question about floating point** - Index(es):