2

I'm in stats class right now and I wanted to know if it makes a difference if you generate a number each digit at a time vs every digit at once, so I wrote some code...

from random import randint
import math

total1 = 0
total2 = 0
for i in range(100000):
    temp = 0
    for j in range(7):
        temp += randint(0,9)*math.pow(10,j)
    total1 += temp
    total2 += randint(0,9999999)

print "avg1 = ", total1/100000
print "avg2 = ", total2/100000

When I ran the code, avg1 was always a decimal and avg2 was always a whole number. I don't understand why total1 is being considered as a double since I only ever added integers to it...

mucle6
  • 645
  • 1
  • 10
  • 24
  • 5
    The result of `math.pow` is a floating-point number, not an integer, and it’s being added to `total1` (through `temp`). – bdesham Jan 21 '15 at 18:43
  • There is an easier way to answer the question. Since in the second method, each digit is drawn independently from the others, the probability distribution over all the numbers will be the product of the distributions of each digit. You are drawing each digit uniformly, so the their product will also be uniform, over the cross-product of all of their domains. That cross-product is the space of all 7-digit positive integers, so the two approaches must yield the same distribution. So only an implementation error could result in them (the distributions) being different. – ely Jan 21 '15 at 18:48

1 Answers1

3

According to the python documentation, the math.pow function returns a floating point number. This is going to implicitly cast the temp variable to be a float as well:

https://docs.python.org/2/library/math.html

Because total1 is implicitly cast as a float, while total2 is consistently used as an int, total1 will return a decimal and total2 will return a whole number.

bagelmakers
  • 384
  • 2
  • 15
  • As an aside, it is important to remember that the / operator in python will not implicitly cast your integers to a double or float. Thus you will receive a rounded answer for total2/100000 while you get a more exact answer for total1/100000 – bagelmakers Jan 21 '15 at 18:49
  • Your comment is true in Python 2 but not in Python 3. I tried in Python 3.4.2 and `type(1000/5)` gives ``. – bdesham Jan 21 '15 at 18:51
  • 1
    what is the syntax to make avg2 not round? – mucle6 Jan 21 '15 at 18:52
  • declaring `total1 = 0.0` and `total2 = 0.0` will initialize them as doubles. You can also explicitly cast them while dividing by: `print "avg1 = ", float(total1/100000)`. See [here](http://stackoverflow.com/questions/2958684/python-division) – bagelmakers Jan 21 '15 at 19:08
  • Also, `from __future__ import division`. – jpkotta Jan 21 '15 at 20:59