vb 遗传算法
Public Function selectoperation()Dim i, j, sortnumber As Integer
Dim p, sum, avfitnessvalue(100) As Double
sum = 0
Randomize (137)
For i = 0 To popsize - 1
sum = sum + fitnessvalue(i) '求种群个体总适应度值
Next i
For i = 0 To opsize - 1
If (sum <> 0) Then
avfitnessvalue(i) = fitnessvalue(i) / sum
'归一化适应度值
End If
Next i
For i = 1 To popsize - 1
avfitnessvalue(i) = avfitnessvalue(i - 1) + avfitnessvalue(i)
Next i
For i = 0 To popsize - 1 '轮盘法选择下代种群个体
avfitnessvalue(i) = avfitnessvalue(i - 1) + avfitnessvalue(i)
Next i
For i = 0 To popsize - 1
p = (1000 * Rnd + 1) / 1000#
sortnumber = 0
Do Until p > avfitnessvalue(sortnumber)
sortnumber = sortnumber + 1
Loop
For j = 0 To chromlength - 1
newpopulationchrom(i, j) = populationchrom(sortnumber, j)
Next j
Next i
For i = 0 To popsize - 1
For j = 0 To chromlength - 1
populationchorm(i, j) = nexpopulationchrom(i, j)
Next j
Next i
End Function
'交叉操作实现
Public Function crossoveroperation()
Dim i, j As Integer
Dim index(150) As Integer
Dim piont, median As Integer
Dim p As Single
Dim ch As Integer
Randomize (137)
For i = 0 To popsize - 1
index(i) = i
Next i
For i = 0 To popsize - 1 '随机重新排列种群中的个体序列
Point = Round((popsize - 1 - i) * Rnd)
median = index(i)
index(i) = index(Point + i)
index(Point + i) = median
Next i
For i = 0 To popsize - 1 Step 2
'按一定的随机概率单点交叉相邻两个体
p = (1000# * Rnd + 1) / 1000#
If (p < pc) Then
Point = chromlength * Rnd
For j = Point To chromlength - 1
ch = populationchrom(index(i), j)
populationchrom(i, j) = populationchrom(idex(i + 1), j)
poplationchrom(index(i + 1), j) = ch
Next j
End If
Next i
End Function
'变异操作实现
Public Function mutionoperation()
Dim i, j As Integer
Dim p As Single
For i = 0 To popsize - 1
'按一定随机概率取反变异点的位置值
For j = 0 To chromlength - 1
p = 1000# * Rnd / 1000#
If (p < pm) Then
If populationchrom(i, j) = 0 Then
populationchrom(i, j) = 1
Else: populationchrom(i, j) = 0
End If
End If
Next j
Next i
End Function
这是我在某篇论文里摘下的VB写的遗传算法代码,想问下怎么添加适应度函数和约束条件。