Вычисление числа пи методом монте карло python

Содержание
  1. Concurrent Monte Carlo Estimate of Pi in Python
  2. Monte Carlo Estimate Pi Sequentially (slowly)
  3. Monte Carlo Estimate for Pi
  4. Monte Carlo Estimate for Pi in Python
  5. Русские Блоги
  6. Метод Монте-Карло для вычисления числа Пи (Python, Java, c подробным объяснением трех способов)
  7. 1. Введение в метод Монте-Карло
  8. 2. Принцип метода Монте-Карло для вычисления числа пи
  9. В-третьих, используйте язык программирования для реализации процесса расчета.
  10. 1. Python реализует метод Монте-Карло для вычисления числа пи
  11. 3. Язык C реализует метод Монте-Карло для вычисления числа пи.
  12. Интеллектуальная рекомендация
  13. Используйте python для загрузки изображений (код для новичков)
  14. Npoi читает пустой Excel пустая однооценная проблема
  15. Реализация Rongyun Chat Server и клиента в практике проектов Android
  16. Инициализация сбора, нет регулировки инициализации ADD () Исключение пустого указателя NullPointException
  17. SIP через NAT SIP через firewall-SBC
  18. Вам также может понравиться
  19. Python --- Получить текст на вкладке DIV
  20. Некоторые небольшие операции примечания WordCloud
  21. STM32
  22. java интервью Вопрос 2
  23. Когда расположение окна переходит на страницу, данные передаются через сообщение
  24. Найти приближённое значение Пи методом Монте-Карло
  25. Решение
  26. Value of Pi using Monte Carlo – PYTHON PROGRAM
  27. Python Code:
  28. OUTPUT:
  29. Monte Carlo animation Python Code:
  30. OUTPUT:

Concurrent Monte Carlo Estimate of Pi in Python

The ProcessPoolExecutor class in Python can be used to estimate Pi by performing multiple Monte Carlo simulations at the same time.

This can dramatically speed-up your program compared to using a single CPU core to run simulations.

In this tutorial, you will discover how to estimate pi using a concurrent implementation of the Monte Carlo method.

After completing this tutorial, you will know:

  • How to estimate the value of Pi using the Monte Carlo method and how to implement it in Python.
  • How to use the ProcessPoolExecutor to manage a pool of worker processes.
  • How to use the ProcessPoolExecutor to improve the estimate of Pi using the Monte Carlo method.

Monte Carlo Estimate Pi Sequentially (slowly)

Pi is a mathematical constant and has an approximate value of 3.14159.

It is defined by the ratio of a circle’s circumference (around the outside) to its diameter (across the middle), and it is used all throughout geometry.

The precision or number of decimal points for Pi does not end, making it a fascinating number.

There are many ways to estimate the value of Pi, but the Monte Carlo method is a particularly interesting method that we can use as the basis for exploring concurrent programming in Python.

Monte Carlo Estimate for Pi

Python has a value of Pi that we can use directly as the Pi constant in the math module.

Nevertheless, we can calculate a value for Pi.

The Monte Carlo method is a statistical technique for estimating quantities using simulations.

There is a standard procedure for estimating Pi using the Monte Carlo method, as follows:

  • Draw a unit square, e.g. width and height are 1.0.
  • Draw a quarter circle, a quadrant, in the square from the top left to the bottom right points.
  • Uniformly scatter points in the square.
  • Count the number of points in the quadrant.
  • Estimate Pi as the ratio of points in the quadrant over the total points multiplied by four.

Monte Carlo Estimate for Pi in Python

We can implement the Monte Carlo estimate of Pi in Python.

First, we need to generate uniformly random points in the unit square.

This can be achieved by using the random.random() function.

Читайте также:  Установка jdk java home

We can call the random() function for both the x and y coordinates of each point. Each point can be defined as a tuple of floating point values and we can generate the desired number of tuples in a list comprehension.

Источник

Русские Блоги

Метод Монте-Карло для вычисления числа Пи (Python, Java, c подробным объяснением трех способов)

1. Введение в метод Монте-Карло

Метод Монте-Карло (метод Монте-Карло), также известный как метод статистического моделирования, является очень важным типом метода численных расчетов, основанного на теории вероятностей и статистики. Относится к использованию случайных чисел (или, чаще, псевдослучайных чисел) для решения многих вычислительных задач.

2. Принцип метода Монте-Карло для вычисления числа пи

Площадь круга больше площади квадрата: π / 4

Поэтому мы используем метод Монте-Карло для случайного разброса точек в квадрате. Точки, попадающие в круг / точки, попадающие в квадрат (все точки), примерно равны площади круга / площади квадрата = π / 4

В-третьих, используйте язык программирования для реализации процесса расчета.

1. Python реализует метод Монте-Карло для вычисления числа пи

import random def count_pi(n): i = 0 count = 0 # n - общее количество набранных баллов while i < n: # Произвольно генерировать координаты x, y x = random.random() y = random.random() # Если x квадрат + y квадрат 

2. Java реализует метод Монте-Карло для вычисления числа Пи π

package practice; /** * * @author ваш плохой бот * @ Почтовый ящик: [email protected] * @ Дата изменения: 2020.1.30 * @ Описание: Используйте метод Монте-Карло для вычисления значения Пи * */ public class MonteCarlo < public double countPI(double n) < int i = 0; int count = 0; double pi = 0; double x = 0; double y = 0; while(i < n) < x = Math.random(); y = Math.random(); if ((x * x) + (y * y) < 1) < count++; >i++; > pi = 4 * (count / n); return pi; > public static void main(String[] args) < // TODO Auto-generated method stub MonteCarlo monteCarlo = new MonteCarlo(); double pi = 0; pi = monteCarlo.countPI(100000); System.out.println («Монте-Карло вычисляет значение Пи:» + пи); >>

3. Язык C реализует метод Монте-Карло для вычисления числа пи.

#include #include #include double countPI(double n) < int i = 0; int count = 0; double pi = 0; double x = 0; double y = 0; srand((unsigned)time(NULL)); while (i < n) < x = rand() / (double)(RAND_MAX); y = rand() / (double)(RAND_MAX); if ((x * x) + (y * y) < 1) < count++; >i++; > pi = 4 * (count / n); return pi; > int main()

Еще в 17 веке люди знали, что «частота» событий используется для определения «вероятности» событий. Это также основная идея метода Монте-Карло. Когда размер выборки достаточно велик, мы можем использовать частоту для оценки вероятности. Это также обычный способ найти коэффициент пи π.

Интеллектуальная рекомендация

Используйте python для загрузки изображений (код для новичков)

Используйте python для загрузки изображений (код для новичков) Вскоре после того, как я только что изучил Python, в коде полно лазеек, и я надеюсь, что вы понимаете Вылезай картинку . .

Npoi читает пустой Excel пустая однооценная проблема

Npoi читает пустой Excel пустая однооценная проблема описание проблемы описание проблемы При чтении Excel через NPOI есть пустая ячейка в Excel, что приведет к тому, что сбор будет меньше, чем количес.

Реализация Rongyun Chat Server и клиента в практике проектов Android

24 апреля 2017 г. 00:58:19 Чтение номера: 2182 1 2 1. Подготовка перед разработкой Прежде всего, мы должны войти на официальный сайт Rongyun, чтобы загрузить соответствующий SDK, и создать соот.

Инициализация сбора, нет регулировки инициализации ADD () Исключение пустого указателя NullPointException

SIP через NAT SIP через firewall-SBC

FireWall&NAT FireWall - это технология пассивной защиты сетевой безопасности, расположенная на границе сети. Запустите стратегию контроля доступа между двумя сетями. Предотвращение не.

Вам также может понравиться

Python --- Получить текст на вкладке DIV

Подготовительный знак знаний Компилировать функцию Функция компиляции используется для компиляции регулярных выражений, генерируют регулярное выражение (рисунок) объекта для совпа.

Некоторые небольшие операции примечания WordCloud

Используйте WordCloud для достижения визуализации данных Здесь вам нужна ваша собственная база данных. Эта база данных представляет собой классическую информацию Douban 250 Изображение обложки: Иди сю.

STM32

STM32 STM32 TIMx_CHx , ( / ) , (TIMx_CNT) / (TIMx_CCRx) , 。 STM32 1: ,FDTS TIMx_CR1 CKD[1:0] , 00 ,FDTS=FCK_INT。 ,TIMx_CCMR1 ICF[3:0] , N , , N=8 , IC1 1 , , , Fck_int , 8 1 , , , , 8 。 , 0000. 2: 。 3.

java интервью Вопрос 2

1. Сортировка пузырьков 2. Печать треугольник 3. Обнаружение строки является численной композицией 4. Форматирование даты Перепечатано: https://www.cnblogs.com/lakeslove/p/7354371.html.

Когда расположение окна переходит на страницу, данные передаются через сообщение

Сначала вставьте код: HTML часть: создать скрытый div js part: создайте форму виртуальной формы через js, отправьте напрямую .

Источник

Найти приближённое значение Пи методом Монте-Карло

Лучший ответ

Сообщение было отмечено mik-a-el как решение

Решение

При помощи метода Монте-Карло определите приближённое значение числа π.
Метод Монте-Карло — общее название группы численных методов, основанных на получении большого числа реализаций стохастического (случайного) процесса, который формируется таким образом, чтобы его вероятностные характеристики совпадали с аналогичными величинами решаемой задачи.

Например, если мы будем случайным образом «бросать» на плоскость точки (случайно выбирать координаты x и y), то чем больше площадь фигуры, тем больше на нее попадёт точек. Если при этом число «бросков» стремится к бесконечности, то отношение количества точек, попавших на две фигуры, будет стремиться к отношению площадей этих фигур.

Из курса математики мы знаем, что площадь круга равна πR2. Значит, чтобы вычислить число π, достаточно узнать площадь круга радиусом 1. Для простоты вычисления возьмём четверть такого круга, лежащую в I квадранте Декартовой плоскости, а потом умножим результат на 4. Таким образом, координаты x и у будут меняться в диапазоне [0, 1].

Добавлено через 1 час 55 минут

import random k = 0.0 for i in range(500000): x = random.random() y = random.random() k += (x * x + y * y  1.0) print(4 * k / 500000)

Источник

Value of Pi using Monte Carlo – PYTHON PROGRAM

One can estimate the value of Pi using Monte Carlo technique. The procedure is really intuitive and based on probabilities and random number generation. I have already written a lot about random number generation in my old posts.

We consider a square extending from x=-1 to x=1 and y=-1 to y=1. That is each side is 2 units long. Now we inscribe a circle of radius 1 unit inside this square, such that the centre of the circle and the square both are at origin. Now, let’s say you drop pins/needles/rice grains or any other thing on the square randomly.

The process of dropping the pins should be completely random and all positions for the landing of the pin should be equally probable. If this is the case, then we can say that the number of pins falling inside the circle (Nc) divided by the total no. of pins dropped on the square (Nt) is given by:

That is the probability of the pin falling inside the circle is directly proportional to the area of the circle. I hope this step is intuitive enough for you.

Well, that’s it. The above relation basically gives you the value of Pi. How?

Well, the area of circle in our case is just (since radius =1 unit). The area of square is 4 units. Therefore, the above equation changes to:

So if we write a program that randomly generates x and y coordinates of the falling pin such that and .

Then the coordinates of the pins that fall inside the circle would satisfy the following relation.

Thus we can count the number of pins falling inside the circle, by incrementing a counter whenever the above relation is satisfied. Finally we can take the ratios of the pins falling inside the circle to the total no. of pins that were made to fall, and use the equation mentioned above to get the value of pi.

The following program illustrates the procedure:

Python Code:

# Author: Manas Sharma # Website: www.bragitoff.com # Email: [email protected] # License: MIT # Value of Pi using Monte carlo import numpy as np # Input parameters nTrials = int(10E4) radius = 1 #------------- # Counter for thepoints inside the circle nInside = 0 # Generate points in a square of side 2 units, from -1 to 1. XrandCoords = np.random.default_rng().uniform(-1, 1, (nTrials,)) YrandCoords = np.random.default_rng().uniform(-1, 1, (nTrials,)) for i in range(nTrials): x = XrandCoords[i] y = YrandCoords[i] # Check if the points are inside the circle or not if x**2+y**2<=radius**2: nInside = nInside + 1 area = 4*nInside/nTrials print("Value of Pi: ",area)

OUTPUT:

Now, that we have seen that the above code works, we can also try to make a pretty animated simulation demonstrating the process.

Monte Carlo animation Python Code:

# Author: Manas Sharma # Website: www.bragitoff.com # Email: [email protected] # License: MIT # Value of Pi using Matplotlib animation import numpy as np import matplotlib matplotlib.use("TkAgg") # set the backend (to move the windows to desired location on screen) import matplotlib.pyplot as plt # from matplotlib.pyplot import figure from matplotlib.pyplot import * fig = figure(figsize=(8, 8), dpi=120) # Input parameters nTrials = int(1E4) radius = 1 #------------- # Counter for the pins inside the circle nInside = 0 # Counter for the pins dropped nDrops = 0 # Generate points in a square of side 2 units, from -1 to 1. XrandCoords = np.random.default_rng().uniform(-1, 1, (nTrials,)) YrandCoords = np.random.default_rng().uniform(-1, 1, (nTrials,)) # First matplotlib window fig1 = plt.figure(1) plt.get_current_fig_manager().window.wm_geometry("+00+00") # move the window plt.xlim(-1,1) plt.ylim(-1,1) plt.legend() # Second matplotlib window plt.figure(2) plt.get_current_fig_manager().window.wm_geometry("+960+00") # move the window # plt.ylim(2.8,4.3) # Some checks so the legend labels are only drawn once isFirst1 = True isFirst2 = True # Some arrays to store the pi value vs the number of pins dropped piValueI = [] nDrops_arr = [] # Some arrays to plot the points insideX = [] outsideX = [] insideY = [] outsideY = [] # Begin Monte Carlo for i in range(nTrials): x = XrandCoords[i] y = YrandCoords[i] # Increment the counter for number of total pins dropped nDrops = nDrops + 1 # Check if the points are inside the circle or not if x**2+y**2<=radius**2: nInside = nInside + 1 insideX.append(x) insideY.append(y) else: outsideX.append(x) outsideY.append(y) # plot only at some values if i%100==0: # Draw on first window plt.figure(1) # The label is only needed once so if isFirst1: # Plot once with label plt.scatter(insideX,insideY,c='pink',s=50,label='Drop inside') isFirst1 = False plt.legend(loc=(0.75, 0.9)) else: #Remaining plot without label plt.scatter(insideX,insideY,c='pink',s=50) # Draw on first window plt.figure(1) # The label is only needed once so if isFirst2: # Plot once with label plt.scatter(outsideX,outsideY,c='orange',s=50,label='Drop outside') isFirst2 = False plt.legend(loc=(0.75, 0.9)) else: #Remaining plot without label plt.scatter(outsideX,outsideY,c='orange',s=50) area = 4*nInside/nDrops plt.figure(1) plt.title('No. of pin drops = '+str(nDrops)+'; No. inside circle = '+str(nInside)+r'; π ≈ $4\frac>>=$ '+str(np.round(area,6))) piValueI.append(area) nDrops_arr.append(nDrops) # For plotting on the second window plt.figure(2) plt.axhline(y=np.pi, c='darkseagreen',linewidth=2,alpha=0.5) plt.plot(nDrops_arr,piValueI,c='mediumorchid') plt.title('π estimate vs no. of pin drops') plt.annotate('π',[0,np.pi],fontsize=20) # The following command is needed to make the second window plot work. plt.draw() # Pause for animation plt.pause(0.1) area = 4*nInside/nTrials print("Final estimated value of Pi: ",area) plt.show()

OUTPUT:

Источник

Оцените статью