Home > Enterprise >  Python loop random integer function
Python loop random integer function

Time:11-18

I'm trying to create a loop that takes an input value, and creates that many random numbers between 0 and 10, and then puts these values throuh a formula in a loop and saves these values into an array. The following is what I've done:

def f(x):
    x**2

def Sample(npts):
    sample = []

    randomlist = random.sample(range(0.0, 10.0), npts)


    for i in range(randomlist):
        y  = f(randomlist)
        sample.append(y)

    print(sample)

now here I am getting an error saying that the sample range is being exceeded. This occurrs when I set npts = 100, can someone explain where I am going wrong? Also, I fear that I may have called the wrong value later down the line. So to explain, I am trying to get 100 random values (npts, in this case) between 0 and 10, and these values be the x values that are put through f(x), (in this case the values being multiplied by 2) and then have these new calculated values saved to the array sample each time and then printed at the end.

Hope that makes what I am trying to do clear, so please let me know how to fix the error!

CodePudding user response:

from random.sample documentation: https://docs.python.org/3/library/random.html#random.sample

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

You are choosing 100 items out of 10 items without replacement, thus there is an error.

If you want to sample with replacement, use random.choices: https://docs.python.org/3/library/random.html#random.choices

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

CodePudding user response:

Study this.

import random


def f(x):
    return x**2


def Sample(npts):
    sample = []

    # Generate random numbers from 0 to 10.
    randomlist = []
    for _ in range(npts):  # just counting from 0 to npts-1
        r = random.random() # random.random() generates numbers from 0 to 1, including 0.2 etc.
        r *= 10  # convert to 0 to 10 range
        assert r >= 0 and r <= 10, "random number r should be in [0, 10]"  # verify that r is in [0, 10]
        randomlist.append(r)  # save to a list

    # Save result of function f
    for v in randomlist: # get each item in the list
        y = f(v)
        sample.append(y)

    return sample


# start
npts = 100
result = Sample(npts)
print(f'result length: {len(result)}')
print(f'result: {result}')

Output

result length: 100
result: [28.4532539113128, 84.86161336289929, 12.483520029172103, ...
  • Related