python随机模块 无范围,(伪)在Python中生成随机数而无需使用模块和时钟

I'm using Python for a competition in which I am creating a bot to play a game. The problem is, it does not have anything of c support installed, so I do not have access to the random, numpy, and scipy modules.

I will have roughly 400mb ram available, and I am looking for a way to produce uniform random numbers between 0 and 1 for simulation purposes during the game.

Note that I have used the clock time before to generate a single number, but the issue is that I will need loads of numbers without the clock changing much, which would result in constantly the same number. In fact, I am limited to a maximum of 1 second for, say, 100k numbers.

I'm considering loading in data, but the problem would then be that the bot would always use the same numbers. Then again, the circumstances for which I need to use the numbers vary slightly.

Using Python 2.7, hoping people have some suggestions.

解决方案

You can use a Mersenne Twister implementation. I found this one, which is modeled after the pseudocode on Wikipedia.

#!/usr/bin/env python2

# -*- coding: utf-8 -*-

"""

Based on the pseudocode in https://en.wikipedia.org/wiki/Mersenne_Twister. Generates uniformly distributed 32-bit integers in the range [0, 232 − 1] with the MT19937 algorithm

Yaşar Arabacı

"""

# Create a length 624 list to store the state of the generator

MT = [0 for i in xrange(624)]

index = 0

# To get last 32 bits

bitmask_1 = (2 ** 32) - 1

# To get 32. bit

bitmask_2 = 2 ** 31

# To get last 31 bits

bitmask_3 = (2 ** 31) - 1

def initialize_generator(seed):

"Initialize the generator from a seed"

global MT

global bitmask_1

MT[0] = seed

for i in xrange(1,624):

MT[i] = ((1812433253 * MT[i-1]) ^ ((MT[i-1] >> 30) + i)) & bitmask_1

def extract_number():

"""

Extract a tempered pseudorandom number based on the index-th value,

calling generate_numbers() every 624 numbers

"""

global index

global MT

if index == 0:

generate_numbers()

y = MT[index]

y ^= y >> 11

y ^= (y << 7) & 2636928640

y ^= (y << 15) & 4022730752

y ^= y >> 18

index = (index + 1) % 624

return y

def generate_numbers():

"Generate an array of 624 untempered numbers"

global MT

for i in xrange(624):

y = (MT[i] & bitmask_2) + (MT[(i + 1 ) % 624] & bitmask_3)

MT[i] = MT[(i + 397) % 624] ^ (y >> 1)

if y % 2 != 0:

MT[i] ^= 2567483615

if __name__ == "__main__":

from datetime import datetime

now = datetime.now()

initialize_generator(now.microsecond)

for i in xrange(100):

"Print 100 random numbers as an example"

print extract_number()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值