1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import math import random import time,os from matplotlib.pyplot import * import numpy as np
class Metal(): def __init__(self, lower_bound, upper_bound, temperature, descending, formula):
self.lower_bound = lower_bound self.upper_bound = upper_bound self.temperature = temperature self.descending = descending self.x = self.RandX() self.y = 0.0 self.history_x = [] self.history_y = [] self.formula = formula self.best = [0,0] def RandX(self): """ 获取随机 x """ return random.uniform(self.lower_bound, self.upper_bound)
def Smelt(self): """ 冶炼开始 """ x = self.RandX() NewY = eval(self.formula) dE = NewY - self.y if dE >= 0 or math.e ** (dE / self.temperature) > random.uniform(0, 1): self.y = NewY self.x = x if self.best[1] < self.y: self.best[0] = self.x self.best[1] = self.y os.system('cls') print '当金属温度为', self.temperature, '℃时,x 到达历史最佳, 为', self.best[0], 'y 为', self.best[1], '\n', '-'*100 self.history_x += [x] self.history_y += [NewY] self.temperature -= self.descending
def PlotAndSave(self): ''' 冶炼结束时画出每温度下的 x 与 y ''' x = np.arange(self.lower_bound, self.upper_bound, 0.01) y = eval(self.formula.replace('math','np')) plot(x,y) plot(self.x, self.y, 'o') savefig('Best.jpg') close('all') time.clock()
lower_bound = 0 upper_bound = 9 temperature = 100 descending = 0.01 formula = 'x + 10 * math.sin(5 * x) + 7 * math.cos(4 * x)'
metal = Metal(lower_bound, upper_bound, temperature, descending, formula) while metal.temperature > 1: t = time.clock() minute, second = divmod(t, 60) hour, minute = divmod(minute, 60) metal.Smelt() print '当前金属温度为', metal.temperature, '℃', '此温度下最优 x 为', metal.x, 'y 为', metal.y, ' 花费时间 %02d:%02d:%02ds' %(hour, minute, second), ' '*5,'\r', print metal.PlotAndSave() os.system('pause')
|