Deka
Deka

Reputation: 71

Why does python return a 0.0 for a function with a value

def on_base_percentage(h, bb, hbp, ab, sf):
    return float((h + bb + hbp)/(ab + bb + hbp + sf))

print on_base_percentage(1,2,3,4,5)

Why does Python print 0.0 when there is in fact a value to the function?

Upvotes: 0

Views: 4567

Answers (2)

mgilson
mgilson

Reputation: 310097

Your function is basically evaluating:

(1 + 2 + 3)/(4 + 2 + 3 + 5)

or

6 / 14

I'm assuming you're using python2.x which is going to do integer division here (truncating the result to end up with an integer. In this case, the truncated result is 0, which you then use to construct a float (0.0). An easy solution here is to just call float on either the numerator or the denomonator to force true division:

float((h + bb + hbp))/(ab + bb + hbp + sf)

Alternative solutions are enabling true_division:

from __future__ import division  # Needs to be imported first thing!

In that case, dividing integers will use "true division". (neat).

Upvotes: 3

davidlowryduda
davidlowryduda

Reputation: 2559

You must cast to a float before you do the division, not after.

The division is performed, yielding 0 since it's division between integers. You then make 0 a float, printing 0.0 as the result.

Try this way

def on_base_percentage(h, bb, hbp, ab, sf):
    return float(h + bb + hbp)/float(ab + bb + hbp + sf)

print on_base_percentage(1,2,3,4,5)
0.428571428571

Upvotes: 4

Related Questions