Skip to content

python pi

In Python, you can calculate the value of pi (π) using various methods. One common method is to use the math module, which provides a constant for pi. Here’s how you can do it:

import math

pi = math.pi
print(pi)

When you run this code, it will print the value of pi, which is approximately 3.141592653589793.

Alternatively, you can calculate an approximation of pi using various mathematical formulas and algorithms. Here’s an example of using the Monte Carlo method to estimate pi:

import random

def estimate_pi(num_samples):
    inside_circle = 0
    total_samples = num_samples

    for _ in range(num_samples):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)
        distance = x**2 + y**2

        if distance <= 1:
            inside_circle += 1

    return (inside_circle / total_samples) * 4

num_samples = 1000000
estimated_pi = estimate_pi(num_samples)
print(f"Estimated value of pi with {num_samples} samples: {estimated_pi}")

This code will use a Monte Carlo simulation to estimate the value of pi based on the ratio of points that fall inside a unit circle. The more samples you use (larger num_samples), the more accurate the estimation will be.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)