Cha*_*ame 9 c++ python random montecarlo
我试图将一些python代码翻译成C++.代码的作用是运行蒙特卡罗模拟.我认为Python和C++的结果可能非常接近,但似乎发生了一些有趣的事情.
这是我在Python中所做的:
self.__length = 100
self.__monte_carlo_array=np.random.uniform(0.0, 1.0, self.__length)
Run Code Online (Sandbox Code Playgroud)
这是我在C++中所做的:
int length = 100;
std::random_device rd;
std::mt19937_64 mt(rd());
std::uniform_real_distribution<double> distribution(0, 1);
for(int i = 0; i < length; i++)
{
double d = distribution(mt);
monte_carlo_array[i] = d;
}
Run Code Online (Sandbox Code Playgroud)
我在Python和C++中以100x5的随机数运行,然后使用这些随机数进行蒙特卡罗模拟.
在蒙特卡罗模拟中,我将阈值设置为0.5,因此我可以轻松验证结果是否均匀分布.
这是monte carlo模拟的概念草案:
for(i = 0; i < length; i++)
{
if(monte_carlo_array[i] > threshold) // threshold = 0.5
monte_carlo_output[i] = 1;
else
monte_carlo_output[i] = 0;
}
Run Code Online (Sandbox Code Playgroud)
由于monte carlo数组的长度为120,我希望1在Python和C++中看到60 秒.我计算了1s 的平均数,并发现,尽管C++和Python中的平均数约为60,但趋势是高度相关的.而且,Python中的平均数总是高于 C++.
我是否知道这是因为我做错了什么,还是仅仅因为C++和Python中随机生成机制的区别?
我根据发布的代码写了这个:
import numpy as np
length = 1000
monte_carlo_array=np.random.uniform(0.0, 1.0, length)
# print monte_carlo_array
threshold = 0.5
above = 0
for i in range (0,length):
if monte_carlo_array[i] > threshold:
above+=1
print above
Run Code Online (Sandbox Code Playgroud)
这在C++中:
#include <random>
#include <iostream>
int main()
{
const int length = 1000;
std::random_device rd;
std::mt19937_64 mt(rd());
std::uniform_real_distribution<double> distribution(0, 1);
double threshold = 0.5;
double monte_carlo_array[length];
for(int i = 0; i < length; i++)
{
double d = distribution(mt);
monte_carlo_array[i] = d;
}
int above = 0;
for(int i = 0; i < length; i++)
{
if (monte_carlo_array[i] > threshold)
{
above++;
}
}
std::cout << above << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
每次五次运行给出:
Python:
480
507
485
515
506
average:
498.6
C++:
499
484
531
509
509
average
506.4
Run Code Online (Sandbox Code Playgroud)
所以,如果有的话,我发现C++高于python.但我认为这更像是"随机数不均匀分布在少量样本中".
我将长度改为100000,结果仍然在50k左右变化:
Python:
50235
49752
50215
49717
49974
Average:
49978.6
C++:
50085
50018
49993
49779
49966
Average:
49968.2
Run Code Online (Sandbox Code Playgroud)
总而言之,我不认为C++和Python中的随机数实现在"它是如何统一到0.5左右"之间没有任何巨大差异.但我并没有非常研究统计数据(而且很多年前).