Skip to content
QuantReadySign In
#449easySimulation

Monte Carlo Pi Estimation

Time Limit: 5sMemory: 256MB

Problem

Estimate π\pi using Monte Carlo simulation. Generate NN random points uniformly in the unit square [0,1]2[0, 1]^2 and count how many fall inside the unit quarter-circle (x2+y21x^2 + y^2 \leq 1).

π4×points inside quarter-circleN\pi \approx 4 \times \frac{\text{points inside quarter-circle}}{N}

Use a Linear Congruential Generator (LCG) for deterministic pseudorandom numbers:

xn+1=(1103515245xn+12345)mod231x_{n+1} = (1103515245 \cdot x_n + 12345) \bmod 2^{31}

Convert to uniform [0,1)[0, 1): u=x/231u = x / 2^{31}. For each point, draw two consecutive values to get coordinates (u1,u2)(u_1, u_2).

Input Format

Two space-separated integers: N seed

Output Format

The estimate of π\pi, to 4 decimal places.

Examples

Example 1
Input(Two space-separated integers: N seed)
1000 42
Output
3.1240

With 1000 points and seed=42, the LCG produces a pi estimate near 3.124.

Example 2
Input(Two space-separated integers: N seed)
10000 123
Output
3.1376

With 10000 points, the estimate gets closer to the true value.

Constraints

  • 100 ≤ N ≤ 1000000
  • 0 ≤ seed ≤ 10^9
  • Output to 4 decimal places
Loading interactive editor…