Exemplo n.º 1
0
        public static async void DoPiCalc()
        {
            PiCalc        theCalc = new PiCalc();
            CalcResult    cr      = new CalcResult();
            Task <double> task    = theCalc.CalculateAsync(cr);

            while (!cr.Quit)
            {
                Console.Write("Enter p (pi value), i (iterations) or q (quit) : ");
                string userInput = Console.ReadLine();

                if (userInput != null && userInput.Equals("p"))
                {
                    double diffPercent = Math.Abs((Math.PI - cr.Pi) * 100.0 / Math.PI);
                    Console.WriteLine("Current value for pi : " + cr.Pi + " (" + diffPercent + " % diff.)");
                }
                else if (userInput != null && userInput.Equals("i"))
                {
                    Console.WriteLine("Iterations so far : " + cr.Iterations);
                }
                else if (userInput != null && userInput.Equals("q"))
                {
                    cr.Quit = true;
                }
            }

            double finalPi = await task;

            Console.WriteLine("Final value for pi : " + finalPi);
            Console.WriteLine("Found after " + cr.Iterations + " iterations");
        }
Exemplo n.º 2
0
        public async Task <double> CalculateAsync(CalcResult cr)
        {
            Random _generator = new Random();
            int    inside     = 0;
            double piCurrent  = 0.0;

            await Task.Run(() =>
            {
                for (long i = 1; i <= 1000000000000 && !cr.Quit; i++)
                {
                    double x = _generator.NextDouble();
                    double y = _generator.NextDouble();

                    if (x *x + y *y < 1.0)
                    {
                        inside++;
                    }

                    piCurrent     = inside * 4.0 / i;
                    cr.Pi         = piCurrent;
                    cr.Iterations = i;
                }
            });

            return(piCurrent);
        }