【问题标题】:Parsing Complex Mathematical Functions in Python在 Python 中解析复杂的数学函数
【发布时间】:2017-02-28 23:10:37
【问题描述】:

Python 中有没有一种方法可以解析 Python 中描述 3D 图的数学表达式?是否使用其他数学模块。我似乎找不到处理两个输入的方法。

我想要解析的函数示例是Holder Table Function

它有多个输入,三角函数,我也需要解析 abs() 部分。

我有两个 2D numpy 网格网格作为 x1 和 x2 的输入,并且希望将它们直接传递给表达式以供其计算。

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 你的数学表达式会采用什么形式?一个字符串?当然,没有内置的方法。我也从未听说过有图书馆可以做到这一点。
  • 是的,它会是一个字符串。我看到 Sympy 将字符串解析为符号,但我很难看到与多个输入相关的内容
  • 我是不是做错了什么,因为我被否决了?
  • 我没有投反对票,但你的问题很模糊。你应该给出输入和预期输出的例子。它有几票赞成票广泛。如果你能举出更具体的例子,这个问题就会得到更多的关注和更好的接受。

标签: python parsing numpy math expression


【解决方案1】:

直接编写numpy 代码来评估这个公式并不难。

def holder(x1, x2):
    f1 = 1 - np.sqrt(x1**2 + x2**2)/np.pi
    f2 = np.exp(np.abs(f1))
    f3 = np.sin(x1)*np.cos(x2)*f2
    return -np.abs(f3)

在某一点评估:

In [109]: holder(10,10)
Out[109]: -15.140223856952055

在网格上评估:

In [60]: I,J = np.mgrid[-bd:bd:.01, -bd:bd:.01]
In [61]: H = holder(I,J)

快速-n-肮脏的同情

无需阅读大量文档即可进入 sympy

In [65]: from sympy.abc import x,y
In [69]: import sympy as sp
In [70]: x
Out[70]: x
In [71]: x**2
Out[71]: x**2
In [72]: (x**2 + y**2)/sp.pi
Out[72]: (x**2 + y**2)/pi
In [73]: 1-(x**2 + y**2)/sp.pi
Out[73]: -(x**2 + y**2)/pi + 1
In [75]: from sympy import Abs
...
In [113]: h = -Abs(sp.sin(x)*sp.cos(y)*sp.exp(Abs(1-sp.sqrt(x**2 + y**2)/sp.pi)))
In [114]: float(h.subs(x,10).subs(y,10))
Out[114]: -15.140223856952053

或者按照帝斯曼的建议

In [117]: h1 = sp.sympify("-Abs(sin(x)*cos(y)*exp(Abs(1-sqrt(x**2 + y**2)/pi)))")
In [118]: h1
Out[118]: -exp(Abs(sqrt(x**2 + y**2)/pi - 1))*Abs(sin(x)*cos(y))
In [119]: float(h1.subs(x,10).subs(y,10))
Out[119]: -15.140223856952053
...
In [8]: h1.subs({x:10, y:10}).n()
Out[8]: -15.1402238569521

现在如何将它与 numpy 数组一起使用?

Evaluating the result of sympy lambdify on a numpy mesgrid

In [22]: f = sp.lambdify((x,y), h1,  [{'ImmutableMatrix': np.array}, "numpy"])
In [23]: z = f(I,J)
In [24]: z.shape
Out[24]: (2000, 2000)
In [25]: np.allclose(z,H)
Out[25]: True
In [26]: timeit holder(I,J)
1 loop, best of 3: 898 ms per loop
In [27]: timeit f(I,J)
1 loop, best of 3: 899 ms per loop

有趣——速度基本一样。

较早的答案是:How to read a system of differential equations from a text file to solve the system with scipy.odeint?

【讨论】:

  • 错字:表达式中缺少 sqrt
  • 我可能会看看我是否可以从中概括它,问题是它可能是遵循类似格式的任何表达式
猜你喜欢
  • 2017-05-07
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多