实现方程矩阵:使用循环定义函数(Python)

2024-04-27 07:41:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在上下文中,我基本上使用的是一个数值积分,它接受一组定义为函数的微分方程。这些函数的一大组遵循一个规则模式,我想在循环中定义它们(或者以任何最合适的方式)。例如:

#system coordinates
s = [y1,y2]

#system equations
def e1(s):
    x1 = s[1]**2 + 1
    return x1

def e2(s):
    x1 = s[2]**2 + 2
    return x1

#equations of motion
eom = [e1,e2]

并不是所有的函数都会遵循精确的模式,对于那些这样的函数,虽然理想情况下我需要这样的东西

def en(s)
    x1 = s[n]**2 + n
    return x1

可以在“n”值的范围内进行迭代。谢谢你的建议


Tags: 函数return定义规则def方式模式system
2条回答

我将使用partial,将值绑定到函数参数:

import functools

def e1(s, n, v1, v2):
    x1 = s[n]**v1 + v2
    return x1

[functools.partial(e1, n=i, v1=2, v2=1) for i in range(10)] # this was your first example

#your second example
[functools.partial(e1, n=n, v1=2, v2=n) for n in range(10)]

为什么不简单地在函数中使用第二个参数,比如:

def en(s, n)
    x1 = s[n]**2 + n
    return x1

result = []
for i in range(100):  # 100 is just for illustration purposes..
    result[0] = en(s, i)  # you do not have to store them in a list. just an example

相关问题 更多 >