Reputation: 873
For instance, this works to return N data points according to the function timestwo(x), but fails to use the whole mymin to mymax range because random.random() returns floats between 0.0 and 1.0. Any advice?
def GenerateDataFromFunction(N,mymin,mymax,myfunc):
out = []
while len(out) < N:
inputvar = myfunc(random.random())
if inputvar > mymin and inputvar < mymax:
out.append(inputvar)
return out
def timestwo(x):
return 2*x
GenerateDataFromFunction(10,0,15,timestwo)
Upvotes: 2
Views: 472
Reputation: 2884
If you just want random numbers between mymin
and mymax
you can use random.randrange(mymin, mymax)
. This would only constrain the input though and not the output. It's not going to be possible to always return outputs in the range since that requires insight into how myfunc
is implemented. For example, your min and max might be 0 and 1 respectively and the function could always return -1 and therefore no matter what arguments you pass it as inputs it will never produce correct outputs. E.g:
def myFunc(arg1):
return -1
GenerateDataFromFunction(10, 0, 1, myFunc) # This never returns
Upvotes: 1
Reputation: 38116
The simplest solution is to generate a list of discrete values along the function and within the range then use random.choice()
.
Upvotes: 0