Alex Young
Alex Young

Reputation: 23

I'm learning Python and why is a floating-point used in this example?

http://learnpythonthehardway.org/book/ex4.html

There's an extra credit question asking me to explain why the floating-point 4.0 is used instead of 4.

I understand that a floating point is used for accuracy, but I can't fathom why it is necessary in any case in this example.

Upvotes: 2

Views: 138

Answers (4)

tzaman
tzaman

Reputation: 47800

There doesn't actually seem to be any need for a float instead of an int in that particular example. It could have an effect if you were to divide something by it, but that's not happening here. (And even then, it'd depend on whether you were using Python 2 or 3, as float division is the default in 3).

If you look at the comments below, zedshaw (the author) admits as much:

Михаил Груздев: And why 4.0 used for space? Maybe it's drivers variable value should be floating-point?

zedshaw: Simply to introduce floating point as a little puzzle. Mathematically the exercise doesn't make much sense, it's just practice. Continue on for now.

Upvotes: 4

CaldwellYSR
CaldwellYSR

Reputation: 3196

This is because of something called Integer Division. Basically this means that if you divide two integers, the resulting number must be an integer. So, for example 3/4 would result in 0 and 4/3 would result in 1. This is because 3/4 in "real" math would give you 0.75 and to turn 0.75 into and integer, Python truncates the floating point values and leaves you with 0.

The easiest way to fix this is to use 4.0 instead of 4. Turning the integer into a float and disregarding Integer Division because integer divided by float results in a float. 3/4.0 equals 0.75 like you want it to.

Upvotes: 0

Abhinav Sarkar
Abhinav Sarkar

Reputation: 23802

A floating point is used because in Python an int divided by an int produces an int (integer division) which is not intended here. If you divide a float by an int or an int by a float, you get a float.

Example:

   4/3
=> 1
   4.0/3
=> 1.3333333333333333
   2*4/3
=> 2
   2*4.0/3
=> 2.6666666666666665

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

Arithmetic with integer operands has an integer result.

>>> 3 / 2
1

Upvotes: -1

Related Questions