【问题标题】:How to plot a defined function against one of its arguments in Python如何在 Python 中根据其参数之一绘制已定义的函数
【发布时间】:2016-09-26 02:33:58
【问题描述】:
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 的函数。我尝试通过矢量化函数并为时间步长 dt 创建一个数组,但得到错误“ValueError: setting an array element with a sequence。”

【问题讨论】:

    标签: python numpy matplotlib runge-kutta


    【解决方案1】:

    问题是你的返回值E不是一个数字,而是一个numpy数组。

    Vectorizing many arrays 会给你一个列表,向量化许多 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-07
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多