D. Caan
D. Caan

Reputation: 2019

How to generate random values for a predefined function?

I have a predefined function, for example this:

my_func = lambda x: (9 * math.exp((-0.5 * y) / 60))/1000

How can I generate random values against it so I can plot the results of the function using matplotlib?

Upvotes: 2

Views: 76

Answers (2)

Ofer Sadan
Ofer Sadan

Reputation: 11922

Depends what you want to do, but the random module is where you want to search. For example, testing it with 100 values between 0 and 1:

import random
my_func = lambda y: (9 * math.exp((-0.5 * y) / 60))/1000
values = [my_func(random.random()) for _ in range(100)]

Or the same thing with 1000 integers between 50 and 250:

import random
my_func = lambda y: (9 * math.exp((-0.5 * y) / 60))/1000
values = [my_func(random.randint(50, 250)) for _ in range(1000)]

The module's documentaion might help: here

The same thing could be achieved with numpy for large datasets, but again, it depends on what exactly you need here

P.S I corrected your lambda to actually use the y value instead of x, i assume it's just a typo

Upvotes: 0

mozway
mozway

Reputation: 260300

If you want to plot, don't use random x values but rather a range.

Also you should use numpy.exp that can take a vector as input and your y in the lambda should be x (y is undefined).

This gives us:

import numpy as np
import matplotlib.pyplot as plt

my_func = lambda x: (9 * np.exp((-0.5 * x) / 60))/1000

xs = np.arange(-1000,10)

plt.plot(xs, my_func(xs))

output:

enter image description here

Upvotes: 3

Related Questions