[Tutor] Floating decimal question

Neil Cerutti neilc at norwich.edu
Tue Dec 19 09:11:43 EST 2017


On 2017-12-18, Roger Lea Scherer <rls4jc at gmail.com> wrote:
> This is my first time in this "forum", please be patient I will do my best.
>
> As I was going through a book and came across this challenge, I did what I
> believe was a success. And I know there are ways of making the decimal
> place be limited to 2 places, but my question is more of understanding why
> the following happened.
>
> This is the code I wrote in python:
>
> bill = float(input("What is the price of the bill?: "))
> tip15 = bill*1.15
> tip20 = bill*1.20
>
> print("Bill plus 15% gratuity is " + str(tip15))
> print("Bill plus 20% gratuity is " + str(tip20))
>
> This is the result I got after I ran the code in an IDE
> (obviously) and then entered 29.99 in the first line:
>
> What is the price of the bill?: 29.99
> Bill plus 15% gratuity is 34.488499999999995
> Bill plus 20% gratuity is 35.988
>
> My question is why does the 15% gratuity go so far beyond the
> decimal place when really there should only be 4 places because
> of multiplication rules, you know, and I do understand
> sometimes things work behind the scenes that you don't see, but
> on the 20% gratuity it gives the "right" answer? So I guess I'm
> just asking why did this happen like this?

Decimal notation cannot represent every rational number. For
example, you cannot write 1/3 in a straight-forward way, since
the digit 3 repreats infinitely. Alan has given you a link which
gives a lot more detail, but the gist is that the floating point
representation computers use has an analogous limitation. It
feels surprising at first because some of the numbers it can't
represent in a finite way do have finite representations in
decimal notation.

For your specific problem, you can use Python's format function,
for example:
 
>>> for i in range(1, 11):
        print('{:.4f}'.format(1 / i))

	
1.0000
0.5000
0.3333
0.2500
0.2000
0.1667
0.1429
0.1250
0.1111
0.1000

-- 
Neil Cerutti



More information about the Tutor mailing list