gpt4 book ai didi

c++ - 为什么我的程序不近似 pi?

转载 作者:行者123 更新时间:2023-11-27 23:47:29 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,通过使用两个随机数互质的概率 6/pi^2 来近似 pi,所以我应该能够将 pi 近似为 sqrt(6/probability) 但出于某种原因它不倾向于 pi 而似乎倾向于 3.912。我试过 rand() 函数,也试过 mersenne twister 随机数生成器,但它们都给我类似的结果。这是怎么回事?这是我的 C++ 代码

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <algorithm>

using namespace std;

int main()
{
srand(time(0));
int times;

cout << "enter number of times: ";
cin >> times;

for(int i = 0; i <= times; i ++)
{
double pi_approx, probability;
int num1, num2, number_of_coprime;
num1 = rand();
num2 = rand();
if(__gcd(num1, num2)>1)
{
number_of_coprime++;
}

probability = double(number_of_coprime)/double(i);
pi_approx = sqrt(6/probability);

cout <<100*i/times<< "% number of coprimes: "<< number_of_coprime << " pi approximation: " << pi_approx<<endl;

}

return 0;
}

最佳答案

您需要在适当的范围内声明变量,正确的公式是随着次数趋于无穷大概率趋于 6/pi^2。试试下面的代码:

int main()
{
srand(time(0));

//for (int times = 100; times < 1000; ++times)
int times = 1000000;
{
double pi_approx, probability;
int number_of_coprime = 0;
for (int i = 0; i < times; i++)
{
int num1, num2;
num1 = rand() % times;
num2 = rand() % times;
if (__gcd(num1, num2) == 1) // increment if coprime !!
{
number_of_coprime++;
}
}
probability = double(number_of_coprime) / double(times);
pi_approx = sqrt(6 / probability);
cout << pi_approx << endl;
}

return 0;
}

输出是:

3.14179

关于c++ - 为什么我的程序不近似 pi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49484541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com