在数值计算中有时候需要合成复杂的公式,这些公式非多项式,但是有着递推公式却无法用一般的for循环生成。以下代码适用于在python中生成拥有递推公式的函数(以Ackley函数为例):
Ackley函数如下:
如下令d(维度)=5:
'''不可矢量和ackley'''
import numpy as np
x=[0, 0, 0, 0, 0]
def assign(x):
dim=len(x)
terms = [f'x{i}' for i in range(1, dim + 1)]
str_assign = ','.join(terms) + ' = x'
return str_assign
str_assign=assign(x)
exec(str_assign)
def formula_ackley_func(x):
dim=len(x)
terms = [f'x{i}**2' for i in range(1, dim+1)]
term_str = ' + '.join(terms)
part1 = f'-20 * np.exp((-0.2 * np.sqrt({term_str}) / {dim}))'
terms = [f'np.cos(2*np.pi*x{i})' for i in range(1, dim+1)]
term_str = ' + '.join(terms)
part2 = f'-np.exp(({term_str}) / {dim})'
formula = f'{part1} {part2} + 20 + np.e'
return formula
formula=formula_ackley_func(x)
a=eval(formula)
print(a) # expected output: 4.44089209850063e-16