From 5fc910fd17d676ac65b25570b5c25a05996aca96 Mon Sep 17 00:00:00 2001 From: SimpleArt <71458112+SimpleArt@users.noreply.github.com> Date: Tue, 29 Dec 2020 19:33:04 -0500 Subject: [PATCH] Added customizable weighted random method --- src/attributes.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/attributes.py b/src/attributes.py index ded89d6..768f28e 100644 --- a/src/attributes.py +++ b/src/attributes.py @@ -204,6 +204,17 @@ class Attributes: #===========================# + def weighted_random(self, weight): + """Returns a random value between 0 and 1. Returns values between the weight and the + nearest of 0 and 1 less frequently than between weight and the farthest of 0 and 1. + """ + rand_num = random.random() + if rand_num < weight: + return (1-weight) * rand_num / weight + else: + return 1 - weight * (1-rand_num) / (1-weight) + + def dist(self, chromosome_1, chromosome_2): """Default distance lambda. Returns the square root of the difference in fitnesses.""" return sqrt(abs(chromosome_1.fitness - chromosome_2.fitness))