Max I.
Max I.

Reputation: 47

How does addition/subtraction of float numbers work in Python?

I don't understand what is going on in the following lines of code:

>>> 123456789012345678. -123456789012345677.
0.0

Shouldn't the result be 1.0?

Thanks. Cheers :)

Upvotes: 0

Views: 5574

Answers (4)

DigitalRoss
DigitalRoss

Reputation: 146053

Floating point numbers are stored as 53 bits1 of mantissa plus 11 bits of exponent, plus a sign bit. enter image description here

Your numbers require more than 53 bits to represent, so the nearest actual representable floating point value is used.

Floating point numbers usually model real-world measurements or simulations of real-world systems. Few if any physical constants or measurements are known to anything even close to 52 bits of precision, so this normally works out OK.


1. The 53rd bit is a hidden bit but it isn't enough to help you:
$ dc
2 52^p
4503599627370496
2 53^p
9007199254740992
123456789012345678 <<<< your number is bigger, actually, it requires about 56 bits:
2o 2 53^1-p
11111111111111111111111111111111111111111111111111111
123456789012345678p
110110110100110110100101110100110001100001111001101001110

Upvotes: 3

bua
bua

Reputation: 4870

Float arithmetics has common issue of rounding problem.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 837956

There is no exact representation of 123456789012345678 as a float:

>>> 123456789012345678.
1.2345678901234568e+17
                 ^ oops

Upvotes: 3

Raymond Hettinger
Raymond Hettinger

Reputation: 226181

Floats only store 53 bits of information, so you are being affected by round-off.

Use integers instead:

>>> 123456789012345678 - 123456789012345677
1

Or use the Decimal module:

>>> from decimal import Decimal
>>> Decimal('123456789012345678.0') - Decimal('123456789012345677.0')
Decimal('1.0')

Upvotes: 7

Related Questions