Skip to main content
 首页 » 编程设计

python之定义用于从数据文件求解方程的函数

2025年02月15日8arxive

我完全不熟悉 python,实际上是任何基础编程语言,我使用 Mathematica 进行所有符号和数字计算。我正在学习使用 python 并发现它真的很棒!这是一个我试图解决但毫 headless 绪的问题! 例如我有一个数据文件

0.      1.     
0.01    0.9998000066665778     
0.02    0.9992001066609779     
...     .. 
  

这只是 {t, Cos[2t]}。 我想从这些数据中定义一个函数,并用它来求解 python 中的方程式。我的 Mathematica 直觉告诉我应该像这样定义函数:

    iFunc[x_] = Interpolation[iData, x] 

剩下的工作就很简单了。例如

NDSolve[{y''[x] + iFunc[x] y[x] == 0, y[0] == 1, y[1] == 0}, y, {x, 0, 1}] 
     

轻松求解方程。 (虽然我没有尝试过更复杂的案例)。 现在如何在 python 中完成这项工作以及准确性对我来说是一个重要的问题。那么,现在我想问两个问题。

<强> 1。这是 Mathematica 中最准确的方法吗?

<强> 2。在 python 中解决问题的更准确方法是什么?

这是我为解决 cos(2t) 的定义有效的问题(使用来自 StackOverflow 的大量输入)所做的拙劣尝试:

from scipy.integrate import odeint 
import numpy as np 
import matplotlib.pyplot as plt 
from math import cos 
from scipy import interpolate 
 
data = np.genfromtxt('cos2t.dat') 
 
T = data[:,0]  #first column 
phi = data[:,1]  #second column 
 
f = interpolate.interp1d(T, phi) 
 
tmin = 0.0# There should be a better way to define from the data 
dt = 0.01 
tmax = 2*np.pi 
t = np.arange(tmin, tmax, dt)  
 
phinew = f(t)   # use interpolation function returned by `interp1d` 
 
""" 
def fun(z, t): 
    x, y = z 
    return np.array([y, -(cos(2*t))*x ]) 
"""     
def fun(z, t): 
    x, y = z 
    return np.array([y, -(phinew(t))*x ])     
 
sol1 = odeint(fun, [1, 0], t)[..., 0] 
     
# for checking the plots         
plt.plot(t, sol1, label='sol') 
plt.show() 
 
 
         

*当我使用来自 cos(2t) 数据的插值函数运行代码时,无法正常工作...错误消息告诉

Traceback (most recent call last): File "testde.py", line 30,  
     in <module> sol1 = odeint(fun, [1, 0], t)[..., 0]  
File "/home/archimedes/anaconda3/lib/python3.6/site-packages/scip‌​y/integrate/odepack.‌​py",  
    line 215, in odeint ixpr, mxstep, mxhnil, mxordn, mxords)  
File "testde.py",  
    line 28, in fun return np.array([y, -(phinew(t))*x ]) 
TypeError: 'numpy.ndarray' object is not callable.  

我真的无法破译它们。请帮助...

请您参考如下方法:

在 Mathematica 中,通常的方法很简单

iFunc = Interpolation[iData] 

Interpolation[iData] 已经返回一个函数。