众妙之门玄之又玄，游戏系统中的伪随机和真随机算法实现Python3

马尔可夫链（Markov chain）

``P = 1*c + 2*c(1-c) + 3*c(1-c)(1-2c)+4*c(1-c)(1-2c)(1-3c)``

``````import math

def p_from_c(c):

po, pb = 0, 0
sumN = 0
maxTries = math.ceil(1/c)

for n in range(maxTries):
po = min(1, c*n) * (1-pb)
pb = pb + po
sumN = sumN + n * po

return (1 / sumN) ``````

``````def c_from_p(p):
cu = p
cl = 0.0
p1, p2 = 0, 1
while True:
cm = (cu + cl) / 2
p1 = p_from_c(cm)
if abs(p1 - p2) <= 0.000000001:
break

if p1>p:
cu = cm
else:
cl = cm
p2 = p1

return cm``````

``````fail = 1

print(c_from_p(0.20)*100*fail)

fail = 2

print(c_from_p(0.20)*100*fail)

fail = 3

print(c_from_p(0.20)*100*fail)``````

``````5.570398829877376
11.140797659754751
16.711196489632126``````

真随机(True-Randomization)

``````import random
from collections import Counter
c = Counter()
for _ in range(10000):
c[random.randint(1, 100)] += 1
print(c)
print(c.values())
print(max(c.values()))``````

``````Counter({90: 123, 51: 122, 84: 121, 77: 119, 74: 118, 2: 117, 86: 116, 33: 116, 72: 113, 81: 112, 56: 112, 42: 112, 9: 111, 11: 110, 97: 110, 16: 109, 27: 109, 8: 109, 6: 109, 62: 109, 15: 108, 29: 108, 12: 107, 22: 106, 28: 106, 82: 106, 7: 105, 94: 105, 89: 105, 71: 105, 5: 105, 24: 105, 80: 105, 65: 104, 20: 104, 48: 104, 93: 104, 1: 104, 79: 103, 57: 103, 40: 103, 26: 103, 63: 103, 30: 102, 68: 102, 75: 101, 18: 101, 23: 101, 39: 100, 44: 100, 54: 99, 85: 99, 91: 99, 59: 99, 76: 99, 43: 98, 31: 98, 66: 98, 25: 98, 60: 97, 58: 97, 35: 97, 64: 97, 70: 97, 19: 97, 34: 97, 96: 96, 13: 96, 52: 96, 61: 95, 100: 95, 21: 95, 98: 95, 49: 94, 69: 94, 99: 93, 87: 93, 88: 93, 78: 92, 73: 91, 17: 91, 67: 91, 4: 91, 46: 90, 92: 90, 36: 90, 3: 89, 14: 89, 41: 89, 55: 87, 53: 85, 32: 85, 38: 84, 37: 84, 50: 83, 83: 83, 10: 83, 45: 82, 47: 80, 95: 75})
dict_values([121, 99, 112, 99, 94, 110, 89, 93, 93, 98, 95, 91, 109, 100, 109, 116, 104, 105, 91, 84, 106, 104, 105, 92, 106, 83, 104, 105, 110, 103, 82, 102, 112, 85, 105, 103, 85, 89, 103, 99, 117, 83, 87, 96, 100, 96, 90, 105, 123, 99, 91, 104, 101, 118, 99, 103, 91, 83, 98, 95, 98, 107, 111, 97, 104, 101, 113, 116, 97, 98, 97, 122, 90, 101, 108, 94, 96, 106, 112, 97, 102, 103, 108, 75, 97, 109, 80, 93, 109, 109, 95, 95, 90, 97, 89, 84, 105, 119, 97, 105])
123``````

``````import random
from collections import Counter
c = Counter()
for _ in range(10000):
c[100] += 1
print(c)
print(c.values())
print(max(c.values()))``````

``````Counter({100: 10000})
dict_values([10000])
10000``````

40 声望
4 粉丝
0 条评论