Skip to content

Instantly share code, notes, and snippets.

@nmayorov
Created June 26, 2015 15:56
Show Gist options
  • Save nmayorov/99edcab1f701893755f1 to your computer and use it in GitHub Desktop.
Save nmayorov/99edcab1f701893755f1 to your computer and use it in GitHub Desktop.
leastsqbound on Rosenbrock function with a single bound
from __future__ import print_function
import numpy as np
from leastsqbound import leastsqbound
def fun(x):
return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
def jac(x):
return np.array([[-20 * x[0], 10],
[-1, 0]])
def main():
x0 = np.array([2.0, 2.0])
bounds = [(None, None), (1.5, None)]
x_opt = np.array([1.22437075, 1.5])
f_opt = fun(x_opt)
obj_value_opt = np.dot(f_opt, f_opt)
x, _ = leastsqbound(fun, x0, bounds=bounds, Dfun=jac)
f = fun(x)
obj_value = np.dot(f, f)
x_num, _ = leastsqbound(fun, x0, bounds=bounds)
f_num = fun(x_num)
obj_value_num = np.dot(f_num, f_num)
print(x_opt, obj_value_opt)
print(x, obj_value)
print(x_num, obj_value_num)
# Output:
# [ 1.22437075 1.5 ] 0.0504261878936
# [ 1. 1.83336568] 69.4498361851
# [ 1.22437075 1.50000001] 0.0504261888796
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment