我使用numpy.random.choice模块根据一个函数数组生成一个选择的“数组”:
def f(x):
return np.sin(x)
def g(x):
return np.cos(x)
base=[f, g]
funcs=np.random.choice(base,size=2)此代码将生成一个由两个项组成的“数组”,引用基数组中的一个函数。
我之所以发表这篇文章,是因为我打印了职务和收件的结果:
[<function f at 0x00000225AC94F0D0> <function f at 0x00000225AC94F0D0>]显然,这会以某种形式返回对函数的引用,但我并不理解该表单是什么或如何操作它,这就是问题所在。我想改变函数的选择,使其不再是随机的,而是取决于某些条件,因此它可能是:
for i in range(2):
if testvar=='true':
choice[i] = 0
if testvar== 'false':
choice[i] = 1这将返回一系列待放入以后的函数。
问题是,代码的进一步操作(我认为)需要前面这种形式的函数引用:作为输入,而不是0,1表示的简单数组,我不知道如何使用if语句获得一个表单数组。
对于需要输入的其他代码,我可能完全错了,但我不知道如何修改它,因此我在这里发布它。完整的代码如下:(它是@Attack68 68在Evolving functions in python上提供的代码的一个细微变化),它的目的是存储一个函数,在每次迭代中乘以一个随机函数,并相应地集成。(我已经对引起问题的函数上面的代码发表了评论)
import numpy as np
import scipy.integrate as int
def f(x):
return np.sin(x)
def g(x):
return np.cos(x)
base = [f, g]
funcs = np.random.choice(base, size=2)
print(funcs)
#The below function is where I believe the [<function...>] input to be required
def apply(x, funcs):
y = 1
for func in funcs:
y *= func(x)
return y
print('function value at 1.5 ', apply(1.5, funcs))
answer = int.quad(apply, 1, 2, args=(funcs,))
print('integration over [1,2]: ', answer)下面是我实现一个非随机事件的尝试:
import numpy as np
import scipy.integrate as int
import random
def f(x):
return np.sin(x)
def g(x):
return np.cos(x)
base = [f, g]
funcs = list()
for i in range(2):
testvar=random.randint(0,100) #In my actual code, this would not be random but dependent on some other situation I have not accounted for here
if testvar>50:
func_idx = 0 # choose a np.random operation: 0=f, 1=g
else:
func_idx= 1
funcs.append(func_idx)
#funcs = np.random.choice(base, size=10)
print(funcs)
def apply(x, funcs):
y = 1
for func in funcs:
y *= func(x)
return y
print('function value at 1.5 ', apply(1.5, funcs))
answer = int.quad(apply, 1, 2, args=(funcs,))
print('integration over [1,2]: ', answer)这将返回以下错误:
TypeError: 'int' object is not callable发布于 2019-12-23 18:50:52
If:您正在尝试将对随机选择的函数列表进行操作的原始代码重构为使用与函数列表中的项相对应的随机索引的版本。重构apply.
def apply(x,indices,base=base):
y = 1
for i in indices:
f = base[i]
y *= f(x)
return y...this以某种形式返回对函数的引用,并不是说我理解该表单是什么或如何操作它.
函数是对象,列表包含对对象本身的引用。它们可以通过将它们赋值给名称,然后调用它们或索引列表和调用对象来使用:
>>> def f():
... return 'f'
>>> def g():
... return 'g'
>>> a = [f,g]
>>> q = a[0]
>>> q()
'f'
>>> a[1]()
'g'
>>> for thing in a:
print(thing())
f
g或者你可以把它们传递出去
>>> def h(thing):
... return thing()
>>> h(a[1])
'g'
>>>发布于 2019-12-23 18:35:29
如果仍然希望按原样使用函数apply,则需要保留输入的函数列表。您可以使用这些索引来创建函数列表,而不是提供索引列表。
不要使用apply(1.5, funcs),而是尝试:
apply(1.5, [base(n) for n in funcs])https://stackoverflow.com/questions/59459525
复制相似问题