(Monte Carlo) Monte Carlo method to calculate pi (implemented in java)

1. Introduction to
Monte Carlo method Monte Carlo method (Monte Carlo method), also known as statistical simulation method, was proposed in the mid-1940s due to the development of science and technology and the invention of electronic computers A kind of very important numerical calculation method guided by probability and statistics theory. Refers to the use of random numbers (or more commonly pseudo-random numbers) to solve many computational problems. Corresponding to it is the deterministic algorithm. Monte Carlo method is widely used in financial engineering, macroeconomics, computational physics (such as particle transport calculation, quantum thermodynamic calculation, aerodynamic calculation) and other fields.
2. The principle of calculating the pi ratio π The
ratio of the area of ​​a 1/4 circle to the area of ​​a square can be used to find a value related to π (the principle is to understand a system through a large number of random samples, and then obtain the value to be calculated.)

The code is as follows: `package com.PI;

import java.util.Random;

public class Test_Pi {

/**

  • @param args
    /
    public static void main(String[] args) { int DARTS = 1000
    1000;
    float hits = (float) 0.0;
    float dist;
    float PI;
    Random ra = new Random();
    System.out.println() ;
    long StartTime = System.currentTimeMillis(); //Start time
    for (int i = 0; i <DARTS; i++) { float x = ra.nextFloat(); float y = ra.nextFloat(); dist = (float ) Math.sqrt((x x) + (y y));//The distance from the point to the center of the circle is less than or equal to one, and the point is deemed to fall within the circle if (dist <= 1.0) { hits +=1; } } long EndTime = System.currentTimeMillis();//End time PI = 4 * (hits/DARTS);//Calculate the value of π System.out.println("The value of PI:" + PI);










    System.out.println("The time used is:" + (EndTime-StartTime));//Calculate the final use time
    }

}
Run results:

————————————————
Copyright statement: This article is the original article of the CSDN blogger "The Lion of Babylon", and it follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and This statement.
Original link: https://blog.csdn.net/weixin_44106912/article/details/89365376

Guess you like

Origin blog.csdn.net/weixin_42041819/article/details/100180758