Division by Zero Errors

27,439

Solution 1

When you call float on the division result, it's after the fact the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0 (the float version of 60):

factor = 60.0 / time_interval

Another way would be divide 60 by float(time_interval)

Note this sample interaction:

In [7]: x = 31

In [8]: 60 / x
Out[8]: 1

In [9]: 60.0 / x
Out[9]: 1.935483870967742

Solution 2

Sharth meant to say: from __future__ import python

Example:

>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>>
Share:
27,439
1337holiday
Author by

1337holiday

Some languages I am well versed in are Objective-C, Swift, C,Java,Python,PHP,HTML5, CSS2/3, Javascript, AS3, SQL, SOQL and Ruby.

Updated on June 16, 2020

Comments

  • 1337holiday
    1337holiday almost 4 years

    I have a problem with this question from my professor. Here is the question:

    Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ).

    Here is my code:

    def typing_speed(num_words,time_interval):
        if(num_words >= 0 and time_interval > 0):
            factor = float(60 / time_interval)
            print factor
            return float(num_words/(factor))
    

    I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently.

    Any help is appreciated, thankyou.

  • Bill Lynch
    Bill Lynch over 13 years
    It might also be helpful to comment about "from future import division". mail.python.org/pipermail/tutor/2008-March/060886.html
  • heltonbiker
    heltonbiker almost 12 years
    Or use factor = float(sixty)/time_interval in case sixty was an already declared integer variable instead of a literal.