当前位置:   article > 正文

[Optimization] Codes Answer to online quiz 1

[Optimization] Codes Answer to online quiz 1

Matlab with cvx: 

  1. % Decision Variables
  2. cvx_begin
  3. variables xsb xre xc xs
  4. % Objective Function
  5. maximize(0.04*xsb + 0.06*xre + 0.08*xc + 0.09*xs)
  6. % Constraints
  7. subject to
  8. xsb + xre + xc + xs == 2.5e6
  9. xc + xs <= 2*xsb
  10. xs <= xc
  11. xc <= 1.7*xre
  12. xsb >= 0
  13. xre >= 0
  14. xc >= 0
  15. xs >= 0
  16. cvx_end
  17. % Display the optimal solution
  18. fprintf('Optimal Solution:\n');
  19. fprintf('State Bonds: %.1f euros\n', xsb);
  20. fprintf('Real Estate Loans: %.1f euros\n', xre);
  21. fprintf('Car Loans: %.1f euros\n', xc);
  22. fprintf('Scholarship Loans: %.1f euros\n', xs);

Python:

  1. import cvxpy as cp
  2. # Decision Variables
  3. xsb = cp.Variable()
  4. xre = cp.Variable()
  5. xcℓ = cp.Variable()
  6. xsℓ = cp.Variable()
  7. # Objective Function
  8. objective = cp.Maximize(0.04*xsb + 0.06*xre + 0.08*xcℓ + 0.09*xsℓ)
  9. # Constraints
  10. constraints = [
  11. xsb + xre + xcℓ + xsℓ == 2.5e6,
  12. xcℓ + xsℓ <= 2*xsb,
  13. xsℓ <= xcℓ,
  14. xcℓ <= 1.7*xre,
  15. xsb >= 0,
  16. xre >= 0,
  17. xcℓ >= 0,
  18. xsℓ >= 0
  19. ]
  20. # Solve the problem
  21. problem = cp.Problem(objective, constraints)
  22. problem.solve()
  23. # Display the optimal solution
  24. print("Optimal Solution:")
  25. print(f"State Bonds: {xsb.value:.1f} euros")
  26. print(f"Real Estate Loans: {xre.value:.1f} euros")
  27. print(f"Car Loans: {xcℓ.value:.1f} euros")
  28. print(f"Scholarship Loans: {xsℓ.value:.1f} euros")

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/134725
推荐阅读
相关标签
  

闽ICP备14008679号