因此,我希望创建一个函数,该函数返回一个包含1000个y值的数组,条件是x_0,x_f,函数y(x)和num点需要1000,我该怎么做?
如果您想要可处理任何Python函数的通用代码,则需要使用np.vectorize
来放弃NumPy的快速速度。否则,请尽可能使用np.vectorize
。使用下面的代码,您可以通过universal functions参数进行控制。
vectorize
def value_finder(start, stop, func, num_points=1000, vectorize=False):
nums = np.linspace(start, stop, num_points)
if vectorize:
func = np.vectorize(func)
return func(nums)
import random
def y_func(x):
return (x^2 + 2*x + 1)
def get_1k(x_min, x_max):
x_out = []
for i in range(0, 1000):
x_out.append(y_func(random.randint(x_min, x_max)))
return x_out
random.seed()
print(get_1k(10, 10000))
是用户定义的函数,给定x,它返回从中计算出的y。y_func
返回最大x和最小x之间的y_func 1000次计算。它返回计算值的数组。注意,这可能返回重复的值,并且仅使用整数。如果要使用浮点数,请使用get_1k()
。
random.random()