Published on

I calculated PI using the integrity of a Senior Dev

Authors

In this article, we will explore a unique approach to calculating PI - one of the constants of this universe. Instead of using complex, academic mathematical formulas, we will harness the power of computers and the theory of statistical probability to estimate the value of PI. Very interesting, please read on.

The Original Idea

Let's consider the problem: we have a circle with a radius of 1 (R = 1) drawn on the OXY coordinate axis. The circle is enclosed by a square with a side of 2.

Circle and Square Areas

R = 1

Circle = π * R²

Square = 4 * R²

O(0, 0)

Following the model above.

We have the ratio between the area of the Circle and the Square: Circle / Square = PI _ R^2 / 4 _ R^2

Simplifying, we get => Circle / Square = PI / 4 (1)

On the other hand:

Let P be the probability that a point A(X, Y) with any X, Y such that 0 <= X <= 1; 0 <= Y <= 1 lies within the circle. Then P is determined by the formula

P = n / N (2)

n: Total number of times point A lies within the circle N: Total number of times point A is selected

We also have P = Circle / Square (3)

From (1), (2), (3) => PI / 4 = n / N => PI = 4 * n / N

Implementation with code

Algorithm with Kotlin, try it at https://play.kotlinlang.org/

fun main() {
    val count = 10_000
    var insideCircle = 0
    for (i in 0..count) {
        val randomX = random()
        val randomY = random()
        if (randomX * randomX + randomY * randomY
#include
#include
#include

#define NUM_POINTS 1000000

int main() {
    srand(time(NULL)); // Initialize SEED for random number

    int points_in_circle = 0;
    for (int i = 0; i < NUM_POINTS; i++) {
        double x = (double)rand() / RAND_MAX * 2 - 1;
        double y = (double)rand() / RAND_MAX * 2 - 1;

        if (x*x + y*y <= 1) {
            points_in_circle++;
        }
    }

    double pi_estimate = 4.0 * points_in_circle / NUM_POINTS;
    printf("Giá trị ước tính của pi: %f\n", pi_estimate);

    return 0;
}

Good luck!