Throw random points at a square and count how many land inside a quarter circle: the share estimates π. Here the points are given, so the result can be checked.
What to build
A program that estimates π from points.
Requirements
- Print
inside I of N, thenpi Ewith E = 4 × I ÷ N to 4 decimal places, thenerror D: the distance between E and math.pi, to 4 decimal places.
Input
Line 1: N. Then N lines, each a point x y with 0 ≤ x, y < 1.
Output
Three lines.
Constraints
1 ≤ N ≤ 10000.
Example
Input:
4
0.1 0.1
0.9 0.9
0.5 0.5
0.7 0.7
Output:
inside 3 of 4
pi 3.0000
error 0.1416
Why it works
Random points fall in each region in proportion to its area, so the share inside the quarter circle estimates π/4; the error shows how rough a small simulation is.
Examples
4 0.1 0.1 0.9 0.9 0.5 0.5 0.7 0.7
inside 3 of 4 pi 3.0000 error 0.1416
2 0 0 0.99 0.5
inside 1 of 2 pi 2.0000 error 1.1416
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A point (x, y) is inside the quarter circle when x² + y² ≤ 1.
Hint 2
The quarter circle covers π/4 of the square, so π ≈ 4 × inside ÷ total.
Solution
Show one correct solution (try it yourself first)
from math import pi
n = int(input())
inside = 0
for _ in range(n):
x, y = map(float, input().split())
if x * x + y * y <= 1:
inside += 1
estimate = 4 * inside / n
print(f"inside {inside} of {n}")
print(f"pi {estimate:.4f}")
print(f"error {abs(estimate - pi):.4f}")
Lesson: Simulation: estimating probabilities by experiment →