mirror of
https://github.com/panda3d/panda3d.git
synced 2025-10-03 18:31:55 -04:00
added weighted choice, randFloat
This commit is contained in:
parent
fb3d7ec622
commit
24638f7e96
@ -6,6 +6,7 @@ import operator
|
|||||||
import inspect
|
import inspect
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import random
|
||||||
|
|
||||||
import Verify
|
import Verify
|
||||||
|
|
||||||
@ -839,3 +840,23 @@ def mostDerivedLast(classList):
|
|||||||
#print a,b,result
|
#print a,b,result
|
||||||
return result
|
return result
|
||||||
classList.sort(compare)
|
classList.sort(compare)
|
||||||
|
|
||||||
|
def weightedChoice(choiceList, rng=random.random):
|
||||||
|
"""given a list of (probability,item) pairs, chooses an item based on the
|
||||||
|
probabilities. rng must return 0..1"""
|
||||||
|
sum = 0.
|
||||||
|
for prob, item in choiceList:
|
||||||
|
sum += prob
|
||||||
|
rand = rng()
|
||||||
|
accum = rand * sum
|
||||||
|
for prob, item in choiceList:
|
||||||
|
accum -= prob
|
||||||
|
if accum <= 0.:
|
||||||
|
return item
|
||||||
|
# rand must be ~1., and floating-point error prevented accum from
|
||||||
|
# hitting 0. Return the last item.
|
||||||
|
return item
|
||||||
|
|
||||||
|
def randFloat(a, b, rng=random.random):
|
||||||
|
"""returns a random float in [a,b]"""
|
||||||
|
return lerp(a,b,rng())
|
||||||
|
Loading…
x
Reference in New Issue
Block a user