知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/C C++

[C++] Get area using Monte Carlo method

코방코 2022. 10. 1. 23:01
728x90

● What is the Monte Carlo method?

We can get a complex area by using the Monte Carlo method instead of calculating it using an integral.

The Monte Carlo method outputs a lot of random points within a specified range, 

and counts them if they are within the target area.

Calculates the ratio between the number of times that the point is printed and the counted point.

Then, the area of ​​the target area can be obtained by multiplying this by the area of ​​the specified range.

 

For example, if we want to get the area of the quarter circle like the below picture.

Then, we can set the specified range as a rectangle

{ x | 0 ≤ x ≤ r } and { y | 0 ≤ y ≤ r } 

The pink area is the target area that we want to get.

If the following equation is satisfied, it can be considered to be in the target area.

Therefore, if the above expression is satisfied, counting is performed.

If we print a lot of points that have random values of x and y, 

 

The black points are in the target area and the blue points are not in.

We can get the ratio between the number of times that the point is printed and the counted point.

So, we can get the target area like below.

 

● Code

I wrote the code case of r = 2 and the number of the points = 1,000,000

 

 

The code gets the result : Target Area = 3.141836

Real value = 3.141592

 

The Monte Carlo method has an advantage in that

it is easy to obtain the area of ​a region that is difficult to obtain through integration,

but you should be recognized that it is an approximation due to a random output.

 

I will write a post soon about calculating integral and complex areas by using C++.

 

728x90
반응형

'Code > C C++' 카테고리의 다른 글

[C++] Integration with the Area of Rectangle and Trapezoid  (0) 2022.09.16