Created
June 17, 2022 08:25
-
-
Save Natsu-Akatsuki/7d6fb158cfebc05f03ed9ead1852778a to your computer and use it in GitHub Desktop.
Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from scipy.optimize import minimize | |
def test01(): | |
""" | |
优化单一变量 | |
:return: | |
""" | |
# function to minimize | |
def fun(x): | |
y = x ** 2 - 12 * x + 20 | |
return y | |
x_start = 2.0 | |
result = minimize(fun, x_start, options={"disp": True}) | |
if result.success: | |
print("Success!") | |
# 返回值: | |
# x: solution array, | |
# success: a Boolean flag indicating if the optimizer exited successfully | |
# fun:values of objective function | |
print(f" x = {result.x} y = {result.fun}") | |
else: | |
print("Could not find the solution") | |
def test02(): | |
""" | |
优化多个变量(用列表的形式)+ 提供约束 | |
:return: | |
""" | |
# function to maximize | |
def fun(xy): | |
x = xy[0] | |
y = xy[1] | |
print(x) | |
area = x * y | |
return -area | |
x_start = [50, 50] | |
# 约束 | |
cons = ({'type': 'eq', 'fun': lambda xy: (2 * xy[0]) + xy[1] - 100}) | |
# 约束 | |
bounds = ((1, 100), (1, 100)) | |
result = minimize(fun, x_start, options={"disp": True}, constraints=cons, bounds=bounds) | |
if result.success: | |
print("Success!") | |
# 返回值: | |
# x: solution array, | |
# success: a Boolean flag indicating if the optimizer exited successfully | |
# fun:values of objective function | |
print(f" x = {result.x} y = {result.fun}") | |
else: | |
print("Could not find the solution") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment