我想我遇到了C++标准库中std::poisson_distribution函数的错误行为。
问题:
- 您能确认这确实是一个bug而不是我的错误吗?
- 假设它确实是一个bug,那么标准库中poisson_distribution函数的代码有什么问题?
细节:
以下C++代码(文件poisson_test.cc)用于生成泊松分布的数字:
#include <array>
#include <cmath>
#include <iostream>
#include <random>
int main() {
// The problem turned out to be independent on the engine
std::mt19937_64 engine;
// Set fixed seed for easy reproducibility
// The problem turned out to be independent on seed
engine.seed(1);
std::poisson_distribution<int> distribution(157.17);
for (int i = 0; i < 1E8; i++) {
const int number = distribution(engine);
std::cout << number << std::endl;
}
}
我按以下方式编译这段代码:
clang++ -o poisson_test -std=c++11 poisson_test.cc
./poisson_test > mypoisson.txt
以下是用于分析文件“mypoisson.txt”中随机数序列的Python脚本:import numpy as np
import matplotlib.pyplot as plt
def expectation(x, m):
" Poisson pdf "
# Use Ramanujan formula to get ln n!
lnx = x * np.log(x) - x + 1./6. * np.log(x * (1 + 4*x*(1+2*x))) + 1./2. * np.log(np.pi)
return np.exp(x*np.log(m) - m - lnx)
data = np.loadtxt('mypoisson.txt', dtype = 'int')
unique, counts = np.unique(data, return_counts = True)
hist = counts.astype(float) / counts.sum()
stat_err = np.sqrt(counts) / counts.sum()
plt.errorbar(unique, hist, yerr = stat_err, fmt = '.', \
label = 'Poisson generated \n by std::poisson_distribution')
plt.plot(unique, expectation(unique, expected_mean), \
label = 'expected probability \n density function')
plt.legend()
plt.show()
# Determine bins with statistical significance of deviation larger than 3 sigma
deviation_in_sigma = (hist - expectation(unique, expected_mean)) / stat_err
d = dict((k, v) for k, v in zip(unique, deviation_in_sigma) if np.abs(v) > 3.0)
print d
脚本生成以下图表:
你可以用肉眼看出问题。n = 158处的偏差在统计学上是显著的,实际上是22σ的偏差!
前一个图表的局部放大。
// NB: This case not in the book, nor in the Errata, but should be ok...
- 除了一些非常基本的大学关于接受/拒绝算法的东西,我对手头的问题一无所知,但这种声明让我感到紧张... :o) - Matteo Italia