Coding questions · Toma
Approximate Pi from Random Points
This question evaluates a candidate's understanding of Monte Carlo estimation, basic Euclidean geometry, probability, and numerical reasoning when using random sampling to approximate mathematical constants.
You are given an array pts of points in the unit square. Each point is represented as an array of two numbers [x, y], where 0 <= x <= 1 and 0 <= y <= 1.
A point lies inside the quarter circle of radius 1 if x*x + y*y <= 1.
Write a function approx(pts) that returns an approximation of pi using the fraction of points that fall inside the quarter circle.
Assume:
ptsis nevernullptscontains at least one point- every point has exactly two numeric coordinates
Example function signature:
function approx(pts) {
return 0;
}
Approximate Pi from Random Points
You are given an array pts of points in the unit square [0, 1] x [0, 1]. Each point is represented as [x, y]. A point lies inside the quarter circle of radius 1 centered at the origin if x*x + y*y <= 1.
Use the fraction of points that fall inside the quarter circle to approximate pi. Since the area of the quarter circle is pi / 4 and the area of the unit square is 1, the approximation is:
pi ≈ 4 * (number of points inside the quarter circle) / (total number of points)
Write a function that returns this approximation as a floating-point number.
Constraints
1 <= len(pts) <= 100000- Each point has exactly two numeric coordinates
0 <= x <= 1and0 <= y <= 1for every point
Hints
- First count how many points satisfy
x*x + y*y <= 1. - The ratio
inside / totalestimates the area of the quarter circle, which ispi / 4.