Algorithm for calculating approximate values of pi

By   Calendar icon Aug 10, 2019   Level 1 icon

Description:

Algorithm for calculating approximate values of pi

Preferencesoft

Tags: C#

Algorithm

Here is a program in C# based on this algorithm that calculates an approximate value of pi*1000000000:

The 14-03-2015, To celebrate the number pi (piday 2015), I present my algorithm for calculating approximate values of pi by a purely computational method.

The following algorithm is based on the detection of the contour of a quarter circle in a grid with integer coordinates and calculating the area by adding all the areas of the squares with sides of length equal to 1 whose of one of its vertices is included in this quarter circle.

In detail, it considers a circle with center 0 and with radius r.

To calculate the area of the circle of radius r, a grid with integer coordinates consisting of squares with sides of length equal to 1 is used. Determining the area of a quarter of the disc with the squares that have a vertex inside.

Outline of the circle Area of the quarter disk

Multiplying by 4, this will actually give us pi*r^2. But if we take a radius equal to a power of 10, we obtain directly digits of pi.

Here is a program in C# based on this algorithm that calculates an approximate value of pi*1000000000:

Program

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace piday
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        long r = 1000000000;
        long r2 = r * r;
        long p = 0;

        long x = r + 1;
        for (long y = 0; y <= r; y++)
        {
            long y2 = y * y;
            while (x * x + y2 > r2 && x >= 0)
            {
                x--;
            }
            p += x;
            x++;
        }

        p = p * 4;
        label1.Text = p.ToString();
    }
}
}

For more decimals, simply increase the radius r by taking powers of 10 and you have to work in multi-precision.


CSharp