一、線性規划問題的求最大最小值問題
# 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)
參考鏈接:
2. PuLP—整數規划例子