Implement class method

This commit is contained in:
George Lacey 2017-09-25 19:03:46 +01:00
parent ceb10dbbde
commit c8b34af323

View File

@ -1,32 +1,39 @@
from math import pow, sin, pi
from random import Random
rand = Random()
class Individual(object):
def __init__(self):
self.rand = Random()
self.x = self.rand.uniform(-100000, 100000)
self.y = self.rand.uniform(-100000, 100000)
self.fitness = 0
self.x = rand.uniform(-100000, 100000)
self.y = rand.uniform(-100000, 100000)
@classmethod
def from_params(cls, x, y):
new_individual = Individual()
new_individual.x = x
new_individual.y = y
return new_individual
def __str__(self):
return "x: %f\ty: %f\tfit: %f\n" %\
(self.x, self.y, self.fitness)
def fitness_function(self):
def fitness(self):
x = self.x
y = self.y
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):
temp = self.x
self.x = spouse.x
spouse.x = temp
one = Individual.from_params(spouse.x, self.y)
two = Individual.from_params(self.x, spouse.y)
return one, two
def mutate(self):
if self.rand.randint(1, 10) % 2 == 0:
if rand.randint(1, 10) % 2 == 0:
self.x = self.rand.random()
else:
self.y = self.rand.random()