简单记录下,背景是在c++场景下做的一个功能需要用python做一下复现,其中有一个根据固定输入的哈希值作为种子取随机数(0-1之间的小数)的操作,需要python和c++保持完全一致。
做法如下:
- 保证哈希是一致的
- 可以c++和python都是用cityhash64算法
- 保证随机数算法是一致的,python的random算法用的是梅森旋转算法(用np.random.rand(),用random.random()生成的和c++对不上。。),c++也用对应的,std::mt19937。
- python代码:
random_seed = cityhash.CityHash64(xxx_input) # 右移32位,这是因为梅森旋转算法的种子只能是uint32,而cityhash64生成的是uint64,需要截断 random_seed = random_seed >> 32 import numpy as np np.random.seed(random_seed) print(np.random.rand())
- c++代码:
std::uint64_t random_seed = cityhash.CityHash64(xxx_input) # 右移32位 std::uint32_t random_seed_uint32 = random_seed >> 32; std::mt19937 rng; rng.seed(random_seed_uint32); std::uniform_real_distributionuniform_scaler_; uniform_scaler_ = std::uniform_real_distribution (0.0, 1.0); float rate = uniform_scaler_(rng); std::cout << "rate: " << rate << std::endl;
这两个随机数完全一致。



