Exemplo n.º 1
0
        private double montecarlo(func f, int amt, bool visualise)
        {
            ScatterSeries scatterAbove = new ScatterSeries {
                MarkerType = MarkerType.Plus, MarkerFill = OxyColors.Blue, MarkerStroke = OxyColors.Blue
            };
            ScatterSeries scatterBelow = new ScatterSeries {
                MarkerType = MarkerType.Plus, MarkerFill = OxyColors.Red, MarkerStroke = OxyColors.Red
            };

            double w = f.b - f.a;

            double minh = Math.Min(0, f.getMinHeight());
            double maxh = Math.Max(0, f.getMaxHeight());

            int hitsUpper = 0;
            int hitsUnder = 0;

            Random r = new Random();

            for (int i = 0; i < amt; i++)
            {
                double x = f.a + (w * r.NextDouble());
                double y = minh + ((maxh - minh) * r.NextDouble());

                if (f.function(x) > 0)
                {
                    if (y >= 0 && y <= f.function(x))
                    {
                        if (visualise)
                        {
                            scatterBelow.Points.Add(new ScatterPoint(x, y, 1));
                        }
                        hitsUpper++;
                    }
                    else
                    {
                        if (visualise)
                        {
                            scatterAbove.Points.Add(new ScatterPoint(x, y, 1));
                        }
                    }
                }
                else
                {
                    if (y <= 0 && y >= f.function(x))
                    {
                        if (visualise)
                        {
                            scatterBelow.Points.Add(new ScatterPoint(x, y, 1));
                        }
                        hitsUnder++;
                    }
                    else
                    {
                        if (visualise)
                        {
                            scatterAbove.Points.Add(new ScatterPoint(x, y, 1));
                        }
                    }
                }
            }

            double result = (w * (maxh - minh) * (hitsUpper - hitsUnder)) / amt;

            if (visualise)
            {
                MyModel.Series.Add(scatterAbove);
                MyModel.Series.Add(scatterBelow);
                MyModel.InvalidatePlot(true);
            }

            return(result);
        }