Monte Carlo analysis-use opencv and c++ to calculate the exact pi

effect:

Code:

int main()
{
	Mat img = Mat::zeros(Size(300, 300), CV_8UC3);

	int rect_width = 300;
	int rect_height = 300;
	int circle_radius = 150;

	circle(img, Point(150, 150), 150, Scalar(255, 255, 255));

	int display = 100;
	int rect_count = 0;
	int cir_count = 0;

	int i = 1;
	while(1)
	{
		float r_x = rand()% RAND_MAX*1.0/ RAND_MAX *300;
		float r_y = rand()% RAND_MAX*1.0/ RAND_MAX *300;

		float dist = sqrt(pow(r_x - circle_radius, 2) + pow(r_y - circle_radius, 2));
		if (dist < circle_radius)
		{
			cir_count++;
		}
		else
		{
			rect_count++;
		}

		if (i++%display == 0)
		{
			printf("PI=%f\n", 4.0*cir_count / (rect_count+ cir_count));
			i = 1;
		}

		line(img, Point(int(r_x), int(r_y)), Point(int(r_x), int(r_y)), Scalar(0, 0, 255), 2);
		imshow("img", img);
		waitKey(1);
	}
}

--------------------------------------------------------------------------------------------------------------------

Monte Carlo analysis is a random sampling algorithm, which is more straightforward when applied to the calculation of pi. The algorithm itself is very simple but the logical structure is very complete.

This is the difference between the usual method and methodology. A set of methods can be applied to many fields, and its contribution is more valuable than a specific method.

This code uses an infinite while loop, and it will overflow in the end. You need to construct a large number operation with a linked list yourself, or use a ready-made large number operation library.

Replace rect_count and cir_count with large numbers, and replace printf with a large number output function to output high-precision results.

 

Guess you like

Origin blog.csdn.net/XLcaoyi/article/details/90668666