python根据递推公式动态生成非多项式函数(非线性叠加)

在数值计算中有时候需要合成复杂的公式,这些公式非多项式,但是有着递推公式却无法用一般的for循环生成。以下代码适用于在python中生成拥有递推公式的函数(以Ackley函数为例):

Ackley函数如下:

f(\mathbf{x})=-20\exp\left(-0.2\sqrt{\frac{1}{d}\sum_{i=1}^dx_i^2}\right) - \exp\left(\frac{1}{d}\sum_{i=1}^d\cos(2\pi x_i)\right)+20+\mathrm{e}

如下令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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值