Python – How to Use Random with a Skew

pythonrandom

I am trying to create a very simple evolution algorithm for a creature simulator, what I would like to have is, both creatures have a trait and a dominance level, both noted by ints. their child's trait will be a random number between creature A's trait and creature B's trait then skewed to the more dominant. So if A has a trait of 5 and dominance of 2 and B has a trait of 10 and a dominance of 7, the skew will be -5 so it skews more towards B. Their child is more likely to have a trait of 8 than 6. Is there a good way to do this?
I visualise it ending up like this:
A5-6–7—8—-9—–10B

I can't figure out how much the skew should be until I am able to test the results, so for the time being it's kind of arbitrary.

Thank you everyone for taking the time to help me.

Best Answer

my solution will give you stronger skew for bigger dominance differences:
it is using the fact that raising a value between 0 and 1 to a positive power will skew the result within the same range.
set the fine-tuning, as you see fit.

import random
a_trait = 5
a_dominance = 2
b_trait = 10
b_dominance = 7

target = random.random()
skew = abs(a_dominance - b_dominance) + 1
fine_tuning_multiplier = 0.3
skewed_target = target ** (skew * fine_tuning_multiplier)

trait_delta = abs(a_trait - b_trait)
target_trait = trait_delta * (1 - skewed_target)

if a_dominance > b_dominance:
  val = b_trait - target_trait
else:
  val = a_trait + target_trait

print "val:", int(round(val))

note that in this solution the traits must be sorted. (i.e. a_trait < b_trait)

40 consecutive runs resulted in:
8 8 9 8 9 10 6 7 7 10 8 8 9 9 10 9 9 7 10 6 10 7 10 9 10 10 7 8 8 7 10 5 6 6 9 9 10 10 6 6

Related Topic