0

I made a small python file on my desktop for fun, and I'm frustrated to find that no values are being returned. Here is the code from the file:

def calc(x):
    chance =1
    for i in range(1,x+1):
        chance *= ((365-i)/365)
    return chance * 100

string = calc(23)
print string

And here is what I type into the terminal:

cd Desktop #where file is located 
python py.py #py is the name of the file 

And this is what it returns:

0
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Zach Gold
  • 1
  • 1
  • 1
    This should work. Make sure you're executing the right file with `cat py.py` in your shell? Also, "end me?" It's not so dire as that, is it? – Zev Averbach Jun 21 '17 at 18:49

3 Answers3

2

Since 365 and i are integers, you are performing integer division, which only returns the "whole" part of the result. Since 365-i is lesser than 365 dividing the two will result in 0, and continuously multiplying it by anything will still give 0.

You could use the 365.0 notation to use floating point division, which will eventually generate the result 46.1655742085:

chance = 1
for i in range(1,x+1):
    chance *= ((365.0 - i) / 365.0)
    # Floating point^-----------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Well so on your first iteration your i = 1. 365-1 = 364. 364/365 = 0 because it is integer division in python. So the answer will always give you 0 unless you change it to allow for you to give a float.

Changing 365 to 365.0 will give you your answer

chance = chance * ((365-i)/365.0)

I just changed the 365 to 365.0 and I got

2.23071139399e-05

As my output

Dorilds
  • 418
  • 1
  • 7
  • 15
0

The result is correct in Python2.x. When a/b and a is less than b, result is 0.

Modify 365 to 365.0 it will cast the division result to float

   chance *= ((365-i)/365.0)
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125