Saturday, August 2, 2014

Python, floating points and range()

MIT's MOOC, "A Gentle Introduction to Programming Using Python" has just taught me that Python's range() does not like integers. Actually, it didn't teach me this at all. The reading discussed getting a range of random floating points and then testing that function to determine how many times each random number occurred. The reading didn't say anything about not being able to use range() with floating points. I figured that out when I tried it myself and it didn't work.

Then, as usual, I hopped over to StackOverflow which was full of suggestions that I perceived to be too unduly complex for the reading. Plus, most of the solutions involved integers in range(). This is precisely what I was trying to avoid.

I am completely new to Python but I continue with my mission of making the unnecessarily complex discernable to newbies. Keep that in mind when you read my solution below.

The reading I refer to is here. I don't use those examples. Here are mine:

#first, get some random numbers
import random #kindof like "using" in C#
randList = [] # we'll need this list soon; make it empty for now
def randomness:
          hi = 2.0
          lo = 1.0
          for i in range(10):   #this will print out 10 random numbers
                 x = random.uniform(lo, hi)
                 #generates random floating point between the lo and hi range
                 randList.append(x) # this adds the value in x to the list
           print randList
               
#test randomness() to see how many times each range of random numbers occur
def test(randList):
       count = 0
       for num in randList:
              if num < 1.5: #I want to see how many numbers less than 1.5 are generated
                     count += 1
       print ("There are/is"), count, ("occurrences of floating points less than 1.5.")

Call randomness() and then call test().

I will also post this in GitHub. More info on range() here.

No comments:

Post a Comment