0
return 25.0 * (1 + 16.0/100)

this returns 29.0.
But, when using int() like below,

return int(25.0 * (1 + 16.0/100))

this returns 28

I don't understand why it is 28 instead of 29.

tomow
  • 1
  • 1

3 Answers3

3

The actual result is something like 28.99999999999 which Python rounds to 29.0 for display. However, when converting to an int, the digits after the decimal are simply chopped off, leaving you with 28.

Why is the first result almost, but not quite, 29? Because binary floating-point math cannot precisely represent numbers that are "nice" in decimal, such as 0.16. In binary, this is a repeating fraction that never terminates and as such cannot be precisely represented in finite memory.

So why do we use binary floating-point numbers if they're not accurate? Because the computer has hardware for dealing with them so math is very fast, and they are accurate enough for most purposes. You can use the Decimal.decimal class for exact representation of decimal numbers, but it will make your math slower.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

it is a Problem of try

print 25*(1+16.0/100) - 29

and you will get a very very Little number smaller than Zero.

maybe you should use round instead or in combination of int

print int(round(25*(1+16.0/100)))
am2
  • 380
  • 5
  • 21
0

Casting to an integer in python simply removes the decimal places. To get the rounded integer value you could use

return int(round(25.0 * (1 + 16.0/100)))

This would return 29.

return round(25.0 * (1 + 16.0/100))

This would return 29.0 because the value is still represented as a floating point and has not been cast to an integer.