In [1]:
from math import sin, exp
def func1(x):
return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x/ 2.)
In [3]:
import numpy as np
xArr1 = np.arange(1., 31.)
print xArr1
print "Shape x:", xArr1.shape
yArr1 = np.array([func1(x) for x in xArr1])
print yArr1
print "Shape y:", yArr1.shape
In [4]:
%matplotlib inline
import matplotlib.pyplot as plt
In [5]:
plt.plot(xArr1, yArr1)
plt.grid(True)
plt.axis([0, 30, -15, 5])
plt.show()
In [6]:
from scipy.optimize import minimize
minFunc1Value1 = minimize(func1, 5)
print "Minimized f(x) (standard method): ", round(minFunc1Value1.fun, 3), "for x = ", round(minFunc1Value1.x, 3)
print "Number of iterations: ", minFunc1Value1.nit
In [7]:
minFunc1Value2 = minimize(func1, 2, method = 'BFGS')
print "Minimized f(x) (BFGS method): ", round(minFunc1Value2.fun, 3), "for x = ", round(minFunc1Value2.x, 3)
print "Number of iterations: ", minFunc1Value2.nit
minValuesAnswer1 = np.zeros( (2) )
minValuesAnswer1[0] = round(minFunc1Value2.fun, 2)
print minValuesAnswer1
In [8]:
minFunc1Value3 = minimize(func1, 30, method = 'BFGS')
print "Minimized f(x) (BFGS method): ", round(minFunc1Value3.fun, 3), "for x = ", round(minFunc1Value3.x, 3)
print "Number of iterations: ", minFunc1Value3.nit
minValuesAnswer1[1] = round(minFunc1Value3.fun, 2)
print minValuesAnswer1
In [9]:
print minValuesAnswer1
with open("AnswerTask1.txt", "w") as fAnswer:
for item in minValuesAnswer1:
fAnswer.write(str(item) + ' ')
In [10]:
from scipy.optimize import differential_evolution
bounds = [(1, 30)]
minFunc1Value4 = differential_evolution(func1, bounds)
print "Minimized f(x) (differential evolution): ", round(minFunc1Value4.fun, 3), "for x = ", round(minFunc1Value4.x, 3)
print "Number of iterations: ", minFunc1Value4.nit
In [11]:
with open("AnswerTask2.txt", "w") as fAnswer:
fAnswer.write(str(round(minFunc1Value4.fun, 2)))
In [12]:
def func2(x): return int(func1(x))
xArr2 = np.arange(1., 31., 0.01)
print xArr2
print "Shape x:", xArr2.shape
yArr2 = np.array([func2(x) for x in xArr2])
print yArr2
print "Shape y:", yArr2.shape
In [13]:
plt.plot(xArr2, yArr2)
plt.grid(True)
plt.axis([0, 30, -15, 5])
plt.show()
In [15]:
minFunc2Value1 = minimize(func2, 30, method = 'BFGS')
print "Minimized f(x) (BFGS method): ", round(minFunc2Value1.fun, 3), "for x = ", round(minFunc2Value1.x, 3)
print "Number of iterations: ", minFunc2Value1.nit
minValuesAnswer2 = np.zeros( (2) )
minValuesAnswer2[0] = round(minFunc2Value1.fun, 2)
print minValuesAnswer2
In [17]:
minFunc2Value2 = differential_evolution(func2, bounds)
print "Minimized f(x) (BFGS method): ", round(minFunc2Value2.fun, 3), "for x = ", round(minFunc2Value2.x, 3)
print "Number of iterations: ", minFunc2Value2.nit
minValuesAnswer2[1] = round(minFunc2Value2.fun, 2)
print minValuesAnswer2
In [19]:
with open("AnswerTask3.txt", "w") as fAnswer:
for item in minValuesAnswer2:
fAnswer.write(str(item) + ' ')
In [ ]: