如何在Python中根据已定义函数的一个参数绘制函数

2024-04-19 03:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

def f(x, t):       #function for x'(t) = f(x,t)
    return -x

def exact(t):       #exact solution
    return np.exp(-t)

def Rk4(x0, t0, dt):      #Runge-Kutta Fourth Order Approximation
    t = np.arange(0, 1+dt, dt)
    n = len(t)
    x = np.array([x0]*n)
    E = np.array([x0]*n)
    E0 = x0-exact(1)
    x[0],t[0],E[0] = x0,t0,E0
    for i in range(n-1):
        h = t[i+1] - t[i]
        k1 = h*f(x[i], t[i])
        k2 = h*f(x[i] + 0.5 * k1, t[i] + 0.5 * h)
        k3 = h*f(x[i] + 0.5 * k2, t[i] + 0.5 * h)
        k4 = h*f(x[i] + k3, t[i+1])
        x[i+1] = x[i] + (k1 + 2.0*(k2 + k3) + k4 )/6.0
        E[i+1] = E[i]+(x[i+1]-x[i])
    return E

vecRk4 = np.vectorize(Rk4)
dtime = np.arange(10e-4,1,10e-5)
S = vecRk4(1.0,0.0,dtime)
plt.plot(dtime,S)

我只是想把x0=1.0,t0=0.0的Rk4函数作为dt的函数。我尝试对函数进行矢量化并为timestep dt创建一个数组,但是得到了错误“ValueError:settinganarray elementwithasequence”


Tags: 函数importreturndefasnpdtk2
1条回答
网友
1楼 · 发布于 2024-04-19 03:26:03

{cd1}但这不是单个数组的问题。你知道吗

Vectorizing 许多数组会给您一个列表,矢量化许多numpy数组在这里不起作用。你知道吗

回到原来的问题:使用矢量化将函数与其参数之一对应的方法是:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

def myfunc(a,b):
    return 2*b+a


vecRk4 = np.vectorize(myfunc)
dtime = np.arange(10e-4,1,10e-5)
S = vecRk4(a=3, b=dtime)
plt.plot(dtime,S)
plt.show()

enter image description here

相关问题 更多 >