Implement class method
This commit is contained in:
parent
ceb10dbbde
commit
c8b34af323
|
@ -1,32 +1,39 @@
|
||||||
from math import pow, sin, pi
|
from math import pow, sin, pi
|
||||||
from random import Random
|
from random import Random
|
||||||
|
|
||||||
|
rand = Random()
|
||||||
|
|
||||||
|
|
||||||
class Individual(object):
|
class Individual(object):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.rand = Random()
|
self.x = rand.uniform(-100000, 100000)
|
||||||
self.x = self.rand.uniform(-100000, 100000)
|
self.y = rand.uniform(-100000, 100000)
|
||||||
self.y = self.rand.uniform(-100000, 100000)
|
|
||||||
self.fitness = 0
|
@classmethod
|
||||||
|
def from_params(cls, x, y):
|
||||||
|
new_individual = Individual()
|
||||||
|
new_individual.x = x
|
||||||
|
new_individual.y = y
|
||||||
|
return new_individual
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "x: %f\ty: %f\tfit: %f\n" %\
|
return "x: %f\ty: %f\tfit: %f\n" %\
|
||||||
(self.x, self.y, self.fitness)
|
(self.x, self.y, self.fitness)
|
||||||
|
|
||||||
def fitness_function(self):
|
def fitness(self):
|
||||||
x = self.x
|
x = self.x
|
||||||
y = self.y
|
y = self.y
|
||||||
n = 9
|
n = 9
|
||||||
self.fitness = pow(15*x*y*(1-x)*(1-y)*sin(n*pi*x)*sin(n*pi*y), 2)
|
return pow(15*x*y*(1-x)*(1-y)*sin(n*pi*x)*sin(n*pi*y), 2)
|
||||||
|
|
||||||
def crossover(self, spouse):
|
def crossover(self, spouse):
|
||||||
temp = self.x
|
one = Individual.from_params(spouse.x, self.y)
|
||||||
self.x = spouse.x
|
two = Individual.from_params(self.x, spouse.y)
|
||||||
spouse.x = temp
|
return one, two
|
||||||
|
|
||||||
def mutate(self):
|
def mutate(self):
|
||||||
if self.rand.randint(1, 10) % 2 == 0:
|
if rand.randint(1, 10) % 2 == 0:
|
||||||
self.x = self.rand.random()
|
self.x = self.rand.random()
|
||||||
else:
|
else:
|
||||||
self.y = self.rand.random()
|
self.y = self.rand.random()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user