Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ZeroDivisionError: float division in python

In the code below: highly simplified. I get ZeroDivisionError: float division Any value below one gives errors. Other times 5/365 gives the error. How do I fix?

import math

def top(  t):
    return ((.3 / 2) * t) / (.3 * math.sqrt(t))


t = 365/365
top= top(t)
print (top)
like image 884
Merlin Avatar asked Sep 20 '11 02:09

Merlin


2 Answers

The problem is here:

t = 365/365

You are dividing two integers, so python is using integer division. In integer division, the quotient is rounded down. For example, 364/365 would be equal to 0. (365/365 works because it is equal to 1, which is still 1 rounded down.)

Instead, use float division, like so.

t = 365.0/365.0
like image 58
cheeken Avatar answered Oct 05 '22 23:10

cheeken


In addition to cheeken's answer, you can put the following at the top of your modules:

from __future__ import division

Doing so will make the division operator work the way you want it to i.e always perform a (close approximation of) true mathematical division. The default behaviour of the division operator (where it performs truncating integer division if the arguments happen to be bound to integers) was inherited from C, but it was eventually realised that it was not a great fit for a dynamically typed language like Python. In Python 3, this no longer happens.

In my Python 2 modules, I almost always import division from __future__, so that I can't get caught out by accidentally passing integers to a division operation I don't expect to truncate.

It's worth noting that from __future__ import ... statements have to be the very first thing in your module (I think you can have comments and a docstring before it, nothing else). It's not really a normal import statement, even though it looks like one; it actually changes the way the Python interpreter reads your code, so it can't wait until runtime to be exectuted like a normal import statement. Also remember that import __future__ does not have any of the magic effects of from __future__ import ....

like image 43
Ben Avatar answered Oct 05 '22 23:10

Ben