• Python数值求解微分方程(欧拉法,隐式欧拉)


    不说什么,先上代码

    这里先求解形如\frac{\mathrm{d} y}{\mathrm{d} x}=f(x,y)的微分方程

    1.欧拉法

    def eluer(rangee,h,fun,x0,y0):
        step = int(rangee/h)
        x = [x0] + [h * i for i in range(step)]
        u = [y0] + [0     for i in range(step)]
        for i in range(step):
            u[i+1] = u[i] + h * fun(x[i],u[i])
        plt.plot(x,u,label = "eluer")
        return u
    2.隐式欧拉法

    def implicit_euler(rangee,h,fun,x0,y0):
        step = int(rangee/h)
        x = [x0] + [h * i for i in range(step)]
        u = [y0] + [0     for i in range(step)]
        v = ["null"] + [0 for i in range(step)]
        for i in range(step):
                v[i+1] = u[i] + h * fun(x[i],u[i])
                u[i+1] = u[i] + h/2 * (fun(x[i],u[i]) + fun(x[i],v[i+1]))
        plt.plot(x,u,label = "implicit eluer")
        return u
    3.三阶runge-kutta法

    def order_3_runge_kutta(rangee,h,fun,x0,y0):
        step = int(rangee/h)
        k1,k2,k3 = [[0 for i in range(step)] for i in range(3)]
        x = [x0] + [h * i for i in range(step)]
        y = [y0] + [0     for i in range(step)]
        for i in range(step):
            k1[i] = fun(x[i],y[i])
            k2[i] = fun(x[i]+0.5*h,y[i]+0.5*h*k1[i])
            k3[i] = fun(x[i]+0.5*h,y[i]+2*h*k2[i]-h*k1[i])
            y[i+1] = y[i] + 1/6 * h * (k1[i]+4*k2[i]+k3[i])
        plt.plot(x,y,label = "order_3_runge_kutta")
        return y
    4.四阶runge-kutta法

    def order_4_runge_kutta(rangee,h,fun,x0,y0):
        step = int(rangee/h)
        k1,k2,k3,k4 = [[0 for i in range(step)] for i in range(4)]
        x = [x0] + [h * i for i in range(step)]
        y = [y0] + [0     for i in range(step)]
        for i in range(step):
            k1[i] = fun(x[i],y[i])
            k2[i] = fun(x[i]+0.5*h,y[i]+0.5*h*k1[i])
            k3[i] = fun(x[i]+0.5*h,y[i]+0.5*h*k2[i])
            k4[i] = fun(x[i]+h,y[i]+h*k3[i])
            y[i+1] = y[i] + 1/6 * h * (k1[i]+2*k2[i]+2*k3[i]+k4[i])
        plt.plot(x,y,label = "order_4_runge_kutta")
        return y
    5.上图

     当然,想要成功操作,得加上这个

    rangee = 1
    fun = lambda x,y:y-2*x/y
     
    implicit_euler(rangee,0.0001,fun,0,1)
    order_4_runge_kutta(rangee,0.0001,fun,0,1)
    order_3_runge_kutta(rangee,0.0001,fun,0,1)
    eluer(rangee,0.0001,fun,0,1)
    plt.legend()
    plt.show()
     

  • 相关阅读:
    ChatGpt提问艺术 prompt工程学习过程
    你见过哪些目瞪口呆的 Java 代码技巧?
    阿里巴巴面试题- - -JVM篇(十五)
    双动子大理石高速直线模组在检测设备中的应用
    【C++】STL-函数对象 + 谓词
    双向链表的实现(增删查改)——最好理解的链表
    nanomsg 广播 问题
    c++中删除map元素的三种方式
    python——使用API
    Springboot+mysql+大学生就业管理系统 毕业设计 -附源码290915
  • 原文地址:https://blog.csdn.net/m0_59485658/article/details/126310098