Sean Ambrose
Sean Ambrose

Reputation: 13

Python loop random integer function

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!

Upvotes: 0

Views: 499

Answers (2)

ferdy
ferdy

Reputation: 5034

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
        r = random.randint(0, 10) # returns integer value randomly in the range [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: [4, 16, 1, 49, 100, 16, 4, 81, 81, ...

Upvotes: 0

adrianop01
adrianop01

Reputation: 600

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.

Upvotes: 1

Related Questions