Arya
Arya

Reputation: 189

random values from specific function python

let's say I want to pull out random values from a linear distribution function, I'm not sure how I would do that.. say I have a function y = 3x then I want to be able to pull out a random value from that line. this is what I've tried:

 x,y = [],[]
 for i in range(10):
    a = random.uniform(0,3)
    x.append(a)
    b = 3*a
    y.append(b) 

This gives me y values that are taken from this linear function (distribution per say). Now if this is correct, how would I do the same for a distribution that looks like a horizontal line?

that is what if I had a horizontal line function y = 3, how can I get random values pulled out from there?

Upvotes: 0

Views: 331

Answers (1)

Cocksure
Cocksure

Reputation: 235

Just define your function, using a lambda or explicit definition, and then call it to get the y-value:

def func(x):
    return 3

points = []
for i in range(10):
    x = random.uniform(0, 3)
    points.append((x, func(x))

A linear function with a slope of 0 in this case is fairly trivial.

EDIT: I think I understand that question a little more clearly now. You are looking to randomly generate a point that lies under the curve? That is quite tricky to directly calculate for an arbitrary function, and you probably will want a bound to your function (i.e a < x < b). Supposing we have a bound, one simple method would be to generate a random number in a box containing the curve, and simply discard it if it isn't under the curve. This will be perfectly random.

def linearfunc(x):
    return 3 * x

def getRandom(func, maxi, a, b):
    while True:
        x = random.uniform(a, b)
        y = random.uniform(0, maxi)
        if y < func(x):
            return (x, y)

points = [getRandom(linearFunc, 9, 0, 3) for i in range(10)]

This method requires knowing an upper bound (maxi) to the function on the specified interval, and the tighter the upper bound, the less sampling misses will occur.

Upvotes: 1

Related Questions