Parsing Complex Mathematical Functions in Python

2024/11/21 2:31:56

Is there a way in Python to parse a mathematical expression in Python that describes a 3D graph? Using other math modules or not. I couldn't seem to find a way for it to handle two inputs.

An example of a function I would want to parse is Holder Table Function.

It has multiple inputs, trigonometric functions, and I would need to parse the abs() parts too.

I have two 2D numpy meshgrids as input for x1 and x2, and would prefer to pass them directly to the expression for it to evaluate.

Any help would be greatly appreciated, thanks.

Answer

It's not hard to write straight numpy code that evaluates this formula.

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

Evaluated at a point:

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

Evaluated on a grid:

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

Quick-n-dirty sympy

Diving into sympy without reading much of the docs:

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

Or with the sympify that DSM suggested

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

Now how do I use this with numpy arrays?

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

Interesting - basically the same speed.

Earlier answer along this line: How to read a system of differential equations from a text file to solve the system with scipy.odeint?

https://en.xdnf.cn/q/118346.html

Related Q&A

How do I check if the user has entered a number? [duplicate]

This question already has answers here:How can I read inputs as numbers?(10 answers)Closed last year.I making a quiz program using Python 3. Im trying to implement checks so that if the user enters a …

high F1 score and low values in confusion matrix

consider I have 2 classes of data and I am using sklearn for classification, def cv_classif_wrapper(classifier, X, y, n_splits=5, random_state=42, verbose=0):cross validation wrappercv = StratifiedKFol…

Replace `\n` in html page with space in python LXML

I have an unclear xml and process it with python lxml module. I want replace all \n in content with space before any processing, how can I do this work for text of all elements.edit my xml example:<…

Basic python. Quick question regarding calling a function [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)Closed 1 year ago.Ive got a basic problem in pyth…

Obtain the duration of a mp4 file [duplicate]

This question already has answers here:How to get the duration of a video in Python?(15 answers)Closed 10 years ago.I need to know the duration of a mp4 file with python 3.3. I search and try to do th…

Matplotlib.pyplot - Deactivate axes in figure. /Axis of figure overlap with axes of subplot

%load_ext autoreload %autoreload 2 %matplotlib inlineimport numpy as np import datetime as dt import pickle import pandas as pd import datetime from datetime import timedelta, date from datetime impor…

How to generate the captcha to train with Python

I would like to use deep learning program for recognizing the captcha using keras with python.But the big challenge is to generate massive captcha to train. I want to solve a captcha like thisHow can …

Convert PNG to a binary (base 2) string in Python

I Basically want to read a png file and convert it into binary(base 2) and store the converted base 2 value in a string. Ive tried so many things, but all of them are showing some error

Turbodbc installation on Windows 10

I tried installing turbodbc and it gives me the following error and not sure whats wrong here.My python version is 3.7My command line output from Windows 10 Pro. C:\Users\marunachalam\Downloads>pip …

how to convert a text into tuples in a list in python

I am a beginner in python and desperately need someones help.I am trying to convert a text into tuples in a list. The original text was already tokenized and each pos was tagged as below:The/DT Fulton/…