【问题标题】:read ODEs into scipy's odeint from textfile从文本文件中将代码读入 scipy odeint
【发布时间】:2017-07-22 20:26:25
【问题描述】:

有没有办法将 ODE 从文本格式读取到 scipy 的 odeint 可以使用的对象中?这是在这里提出的:How to read a system of differential equations from a text file to solve the system with scipy.odeint? 但这个问题不必要地使用了 sympy,还有其他解决方案吗? scipy 的 odeint 期望动态生成一个函数。

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    ODE 必须是 Python 函数。通常使用deflambda 创建。

    eval 可以从字符串创建函数

    In [183]: f=eval('lambda x: x**2')
    In [184]: f(10)
    

    但它被认为是不安全的:Using python's eval() vs. ast.literal_eval()?

    但是安全的替代方法不能创建函数

    In [185]: f=ast.literal_eval('lambda x: x**2')
    ...
    ValueError: malformed node or string: <_ast.Lambda object at 0xa749882c>
    

    有关使用sympy 或直接创建函数的最新讨论,请参阅:Parsing Complex Mathematical Functions in Python


    最干净的解决方案是在文本文件中编写有效的 Python 代码,将其命名为 .py,然后将其导入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多