[Tutor] Floating point exercise 3 from Learn python the hard way

Sander Sweers sander.sweers at gmail.com
Tue Jun 14 16:55:10 CEST 2011


On 14 June 2011 15:20, amt <0101amt at gmail.com> wrote:
>>> But I can't understand at line 2 and 3. I mean it makes no difference
>>> for me. Saying 30 or 30.0 is the same thing.
>>> As well as saying 97 or 97.0.
>>
>> Precisely, thats why I asked the question.
>
> As a beginner at line 2 and 3 I see no point of using floating numbers
> except the fact to serve as an example  that if I have a floating point
> number it affects the rest of the expression evaluation.

Correct, 2 and 3 do not need floating point arithmetic.

> So, should I keep them or not?It's unclear to me and sadly the author of the
> book doesn't provide the solutions to the exercises. The only way I can
> verify myself is using this list.

If you tell Python to divide 2 integers (whole numbers) by default it
will use integer arithmetic. So in your calculation on line 5 you get
a result of 7 as Python does not switch to floating point arithmetic.

You can ask Python to use floating point arithmetic a couple of ways.
For example if you want 2 divided by 3 you can tell Python to use
floating point arithmetic by:

--1--
>>> float(2) / 3
0.6666666666666666
>>> float(20) / 7
2.857142857142857
--2--
>>> 2.0 / 3
0.6666666666666666
>>> 20.0 / 7
2.857142857142857

What happens here is that Python on one side of the division has a
floating point number. This will force it to use floating point
arithmetic instead of integer. Generally the second form is used and
the first is for demonstration purpose only.

>>> 2 / 3
0
>>> 20 / 7
2

Here we have 2 integers and therefor Python uses integer arithmetic
and gives 0 and 2 as result. This is because the results of the
division can not be stored as an integer so everything after the
decimal place gets cut off.

In Python 3 this has been changed that by default it will do floating
point arithmetic. You can also get this in Python 2 by importing
division from __future__.

The Python tutorial [1] on floating point arithmetic will give you
much more info on floating point arithmatic in Python.

Greets
Sander
[1] http://docs.python.org/tutorial/floatingpoint.html


More information about the Tutor mailing list