[英]Parsing Complex Mathematical Functions in Python
Python中有没有一种方法可以解析Python中描述3D图形的数学表达式? 是否使用其他数学模块。 我似乎找不到一种处理两个输入的方法。
我想解析的一个函数示例是Holder Table Function 。
它具有多个输入,三角函数,我也需要解析abs()部分。
我有两个2D numpy网格作为x1和x2的输入,并且希望将它们直接传递给表达式以求值。
任何帮助将不胜感激,谢谢。
编写用于计算此公式的简单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)
无需大量阅读文档即可进入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
或是DSM建议的表现
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 mesgrid上评估sympy lambdify的结果
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
有趣-基本相同的速度。
这方面的早期答案是: 如何从文本文件中读取微分方程系统,以使用scipy.odeint求解该系统?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.