317 字
2 分钟
对宏观经济贫富差距的简单分析

概述#

模型#

Python中的线性规划求解#

本部分内容引自《数学建模算法与应用》

求解如下的线性规划问题:

minz=2x1+3x2+x3min \quad z = 2x_1+3x_2+x_3s.t.x1+x2+x3=7 x1+4x2+2x38 3x1+2x26 x1,x2,x30\begin{aligned} s.t. \quad x_1+x_2+x_3&=7 \\\ x_1+4x_2+2x_3&\geq8 \\\ 3x_1+2x_2&\geq6 \\\ x_1,x_2,x_3&\geq0 \end{aligned}

用Python进行线性规划求解时,

import numpy as np
from scipy import optimize
z = np.array([2, 3, 1])
a = np.array([[1, 4, 2], [3, 2, 0]]
b = np.array([8, 6])
a_eq = np.array([[1, 1, 1]])
b_eq = np.array([7])
x1_bound = x2_bound = x3_bound = (0, None)
bounds = (x1_bound, x2_bound, x3_bound)
res = optimize.linprog(z, A_ub=-a, b_ub=-b, A_eq=a_eq, b_eq=b_eq, bounds=bounds)
print(res)

Python中的非线性规划求解#

详见scipy的官方文档

考虑如下的非线性规划问题:

计算(2+x1)/(1+x2)3x1+4x3(2+x_1)/(1+x_2)-3x_1+4x_3的最小值,这里对任意xix_i均有0.1<xi<0.90.1<x_i<0.9成立。

Python代码如下:

import numpy as np
from scipy import optimize
# 定义目标函数
def func1(nums):
a, b, c, d = nums
def _func0(x):
y = (a+x[0])/(b+x[1]) - c*x[0] + d*x[2]
return y
return _func0
# 有两种方法表示约束
def cons1(nums):
# 'eq'表示等式,'ineq'表示大于等于
x1_min, x1_max, x1_min, x2_max, x3_min, x3_max = nums
_cons = ({'type':'ineq', 'fun':lambda x: x[0]-x1_min},
{'type':'ineq', 'fun':lambda x: x1_max-x[0]},
{'type':'ineq', 'fun':lambda x: x[1]-x2_min},
{'type':'ineq', 'fun':lambda x: x2_max-x[1]},
{'type':'ineq', 'fun':lambda x: x[2]-x3_min},
{'type':'ineq', 'fun':lambda x: x3_max-x[2]})
return _cons
# 法2
bouds = []
for k in range(3):
# 'None'为不限制
bounds.append((0.1, 0.9))
args = [2, 1, 3, 4]
x0 = np.array([0.5, 0.5, 0.5])
res = optimize.minimize(func1(args), x0=x0, constraints=cons1([.1, .9]*3), bounds=bounds)
print(res)
# res.x = [0.9, 0.9, 0.1
# res.success = True]
对宏观经济贫富差距的简单分析
https://blog.xiaobaizhang.top/posts/macro25/
作者
张小白
发布于
2020-01-13
许可协议
CC BY-NC-SA 4.0