Wyznaczanie liczby PI metodą MonteCarlo (tzw. na pałę)
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;
namespace PI_MonteCarlo
{class Program
{staticvoid Main(string[] args){long n;long nk =0;double x, y;float s;
Random r =new Random();
Console.WriteLine("Podaj n: ");
n = Int64.Parse(Console.ReadLine());
for(int i =1; i <= n; i++){
x = r.NextDouble();
y = r.NextDouble();
if(Math.Sqrt((x-1)*(x-1)+(y-1)*(y-1))<=1){
nk++;}
}
s =(float)4* nk / n;
Console.WriteLine(s);
Console.ReadLine();
}}}
Liczenie całki metodą MonteCarlo
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;
namespace Calka_MonteCarlo
{class Program
{staticdouble Funkcja(double x){return-x * x +10;}
staticdouble LiczCalke(int a, int b, int n){
List<double> punktyX = Losuj(n, a, b);double sum =0;
foreach(double punkt in punktyX){
sum += Math.Abs(Funkcja(punkt));}
return(sum / n)* Math.Abs(b - a);}
static List<double> Losuj(int n, int a, int b){
List<double> punkty =new List<double>();
Random r =new Random();
for(int i =0; i < n; i++){
punkty.Add(r.NextDouble()*(b - a)+ a);}
return punkty;}
staticvoid Main(string[] args){
Console.WriteLine(LiczCalke(-3, 3, 10000));
Console.ReadLine();}
}}