官术网_书友最值得收藏!

13. Computing the value of Pi

A suitable solution for approximately determining the value of Pi is using a Monte Carlo simulation. This is a method that uses random samples of inputs to explore the behavior of complex processes or systems. The method is used in a large variety of applications and domains, including physics, engineering, computing, finance, business, and others.

To do this we will rely on the following idea: the area of a circle with diameter d is PI * d^2 / 4. The area of a square that has the length of its sides equal to d is d^2. If we pide the two we get PI/4. If we put the circle inside the square and generate random numbers uniformly distributed within the square, then the count of numbers in the circle should be directly proportional to the circle area, and the count of numbers inside the square should be directly proportional to the square’s area. That means that piding the total number of hits in the square and circle should give PI/4. The more points generated, the more accurate the result shall be.

For generating pseudo-random numbers we will use a Mersenne twister and a uniform statistical distribution:

template <typename E = std::mt19937, 
typename D = std::uniform_real_distribution<>>
double compute_pi(E& engine, D& dist, int const samples = 1000000)
{
auto hit = 0;
for (auto i = 0; i < samples; i++)
{
auto x = dist(engine);
auto y = dist(engine);
if (y <= std::sqrt(1 - std::pow(x, 2))) hit += 1;
}
return 4.0 * hit / samples;
}

int main()
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data),
std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
auto eng = std::mt19937{ seq };
auto dist = std::uniform_real_distribution<>{ 0, 1 };

for (auto j = 0; j < 10; j++)
std::cout << compute_pi(eng, dist) << std::endl;
}
主站蜘蛛池模板: 青神县| 庆云县| 新郑市| 察雅县| 海丰县| 汉源县| 丹阳市| 古蔺县| 临漳县| 庆元县| 沛县| 甘泉县| 怀来县| 龙口市| 岳阳市| 泸定县| 璧山县| 广昌县| 洛宁县| 宝山区| 噶尔县| 西乡县| 会理县| 昭觉县| 精河县| 博爱县| 定结县| 呼和浩特市| 甘洛县| 蓬安县| 连平县| 梁平县| 九江县| 武川县| 通州市| 土默特右旗| 蓬安县| 沅江市| 上高县| 平邑县| 双流县|