实现pi估计量(C ++中的蒙特卡洛方法)

问题描述 投票:-1回答:1

每当我运行程序时,我收到的pi的返回值都会直接增加我输入的点数。我一直在遵循蒙特卡洛pi估计方法,该方法涉及随机生成的0到1之间的数字。

例如,当我运行程序并输入29点时,我的pi估计值为29。

https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/

// piCalculator.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
using namespace std;
double piEstimator(int numPts);

int main()
{
    cout << rand();
    int numPts;
    cout << "How many points would you like to use to estimate pi?" << endl;
    cin >> numPts;

    float piEstimation = piEstimator(numPts);
    cout << "Your estimation for pi is " << numPts << endl;
    return 0;
}

double piEstimator(int numPts) {
    double x, y, dist, piEstimation;
    double dotsCirc = 0;
    double dotsTotal = 0;

    for (int i = 0; i < numPts; i++) {
        x = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
        y = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
        dist =(x * x) + (y * y);
        if (dist <= 1) {
            dotsCirc++;
        }
        dotsTotal++;
        }
    piEstimation = (4*dotsCirc/dotsTotal);
    return piEstimation;
    }

每当我运行程序时,我收到的pi的返回值都会直接增加我输入的点数。我一直在遵循蒙特卡洛pi估计方法,涉及随机...

c++
1个回答
0
投票

您正在打印点数而不是估计的pi。

© www.soinside.com 2019 - 2024. All rights reserved.