zoukankan      html  css  js  c++  java
  • 列举几个python解决数学建模的例子

    一、线性规划问题的求最大最小值问题

    # max: z = 4x1 + 3x2
    # st:      -2x1 - 3x2<=-10
    #          x1 + x2 <=8
    #          x2 <= 7
    #          x1,x2 > 0
    
    from scipy.optimize import linprog
    c = [4,3]        #默认linprog求解的是最小值,若求最大值,此处c取反即可得到最大值的相反数。
    A = [[-2,-3],[1,1]]
    b = [-10,8]
    x1_bounds = [0,None]
    x2_bounds =[0,7]
    res = linprog(c,A,b,bounds=(x1_bounds,x2_bounds))
    print(res)
         con: array([], dtype=float64)
         fun: 10.000000000157014
     message: 'Optimization terminated successfully.'
         nit: 4
       slack: array([-1.24439126e-10,  4.66666667e+00])
      status: 0
     success: True
           x: array([1.40727180e-10, 3.33333333e+00])

    结果只关注第二行和最后一行就可以了,第二行是最优值的大小,最后一行是取得最优值时变量的大小。

    二、多项式的最小二乘法曲线拟合

    import numpy as np
    import matplotlib.pyplot as plt
    x = np.arange(1, 6, 1)
    y = np.array([2, 6, 12, 20, 30])  # y=x^2+x
    #拟合
    print(np.polyfit(x, y, 2))   
    
    #可视化
    f = np.polyfit(x, y, 2)
    p = np.poly1d(f)
    yvals = p(x)
    plt.figure(figsize=(10,8))
    plt.plot(x, y, '.')
    plt.plot(x, yvals)
    plt.xlabel('x轴')   #可以用来标注
    plt.ylabel('y轴')
    plt.show()

    三、方程求导

    import numpy as np
    import scipy as sp
    import scipy.misc
    
    def f(x): return 2*x*x + 3*x + 1
    print(sp.misc.derivative(f, 2))

    四、求不定积分

    import numpy as np
    import scipy as sp
    import scipy.integrate
    
    
    f = lambda x : x**2
    print(sp.integrate.quad(f, 0, 2))
    print(sp.integrate.fixed_quad(f, 0, 2))

    五、求解非线性方程组

    import numpy as np
    import scipy as sp
    import scipy.optimize
    
    def f(x):
        return [5*x[1] + 3, 4*x[0]*x[0], x[1]*x[2] - 1.5]
    
    ans = sp.optimize.fsolve(f, [0, 0, 0])  #实际用起来问题很大,很不准
    print(ans)
    #print(ans[0]*ans[1]*ans[2])
    print(f(ans))

    六、求解线性方程组

    import numpy as np
    import scipy as sp
    import scipy.optimize
    import scipy.linalg
    
    
    a = np.array([[1, 1, 1], [2, 1, 1], [1, -1, 1]])
    b = np.array([2, 3, 6])
    print(sp.linalg.solve(a, b))
    #print(sp.linalg.inv(a).dot(b))  #或利用矩阵运算求解

    七、01整数规划

    # coding=utf-8
    
    from pulp import LpProblem, LpVariable, LpConstraint, LpConstraintLE, LpConstraintGE, LpMaximize, LpBinary, LpStatus
    
    # Create a new model
    m = LpProblem(name="MIP Model", sense=LpMaximize)
    
    # Create variables
    x = LpVariable(cat=LpBinary, name="x")
    y = LpVariable(cat=LpBinary, name="y")
    z = LpVariable(cat=LpBinary, name="z")
    
    # Add constraint: x + 2y + 3z <= 4
    m += LpConstraint(e=(x + 2*y + 3*z), sense=LpConstraintLE, rhs=4, name='c0')
    
    # Add constraint: x + y >= 1
    m += LpConstraint(e=(x + y), sense=LpConstraintGE, rhs=1, name='c1')
    
    # Set objective
    m.setObjective(x + y + 2*z)
    
    # Calculate with the default CBC optimizer
    status = m.solve()
    
    if LpStatus[status] == 'Optimal':
        for v in m.variables():
            print('%s %g' % (v.name, v.varValue))
        print('Obj: %g' % m.objective.value())

    八、网络流-最大流

    import networkx as nx
    
    g = nx.DiGraph()
    # 4
    # 5
    # 0 1 3
    # 0 2 1
    # 1 2 1
    # 1 3 1
    # 2 3 3
    
    n, m = int(input()), int(input())
    
    for i in range(n):
        g.add_node(i)
    
    for _ in range(m):
        a, b, c = [ int(i) for i in input().split(' ') ]
        g.add_edge(a, b, capacity=c)
    
    max_flow = nx.algorithms.flow.maxflow.maximum_flow(g, 0, n-1)[0]
    print("max_flow:", max_flow)

    参考链接:

    1. CSDN-用python做线性规划

    2. PuLP—整数规划例子

    3.  php中文网-数学建模可以用Python吗

    4. CSDN-Python networkx 实现网络流

  • 相关阅读:
    165. Compare Version Numbers
    164. Maximum Gap
    3、桶排序
    162. Find Peak Element
    160. Intersection of Two Linked Lists
    155. Min Stack
    154. Find Minimum in Rotated Sorted Array II
    153. Find Minimum in Rotated Sorted Array
    Linux/Unix系统编程手册 第二章:基本概念
    Linux/Unix系统编程手册 第一章:历史和标准
  • 原文地址:https://www.cnblogs.com/lfri/p/12238409.html
Copyright © 2011-2022 走看看