Потоки. Вычисление числа пи методом Монте-Карло - C#
Формулировка задачи:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace _1_лаб
{
class Program
{
static double sum = 0;
static void Method_Monte_Karlo(object num_p)
{
int n_point = (int)num_p;
double pi;
double n_circle = 0;
Random r = new Random();
for (int i = 0; i < n_point; i++)
{
if (IsPointInCircle(1.0, r.NextDouble(), r.NextDouble()))
{
n_circle++;
}
}
pi = (4 * n_circle) / (double)n_point;
//Console.WriteLine(pi);
}
static bool IsPointInCircle(double R, double x, double y)
{
return ((x * x + y * y) <= R * R);
}
static void Threads(int numThreads, int num)
{
ThreadPool.SetMaxThreads(numThreads, 0);
for (int i = 0; i < numThreads; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Method_Monte_Karlo), num);
}
}
static void Main(string[] args)
{
int numThr;
int _num;
Console.WriteLine("Введите количество потоков: ");
numThr = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите максимальное количество точек: ");
_num = Convert.ToInt32(Console.ReadLine());
Threads(numThr, _num);
Console.ReadKey();
}
}
}Решение задачи: «Потоки. Вычисление числа пи методом Монте-Карло»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MonteCarlo_Method {
class Program {
static List<double> piList = new List<double>();
static List<EventWaitHandle> handles = new List<EventWaitHandle>();
static void Main(string[] args) {
int threadCount = 10;
int pointNumber = 100000;
for (int i = 0; i < threadCount; i++) {
EventWaitHandle handle = new AutoResetEvent(false);
new Thread(delegate() { MonteCarloMethod(pointNumber, handle); }).Start();
handles.Add(handle);
}
WaitHandle.WaitAll(handles.ToArray());
Console.WriteLine("Avarage of Pi is: {0}", piList.Average());
Console.ReadLine();
}
static void MonteCarloMethod(int pointNumber, object handle) {
Random r = new Random();
AutoResetEvent wh = (AutoResetEvent)handle;
double circle = 0;
for (int i = 0; i < pointNumber; i++) {
if(IsCircle(1.0,r.NextDouble(), r.NextDouble())){
circle++;
}
}
piList.Add((4 * circle) / (double)pointNumber);
wh.Set();
}
static bool IsCircle(double radius, double x, double y) {
return ((x * x + y * y) <= radius * radius);
}
}
}