Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Compute Pi with RNG

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Compute Pi with RNG. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

DeepMind research evaluation code sometimes needs a reproducible numerical baseline. Implement an adaptive Monte Carlo estimator for pi by sampling points uniformly from the unit square and measuring how many fall inside the quarter circle.

Use the specified 32-bit linear congruential generator rather than Python's global random state. For each sample, generate two values in [0, 1), compute x² + y², and classify the point as inside when the value is at most 1.

After each sample, estimate pi as 4 * inside / samples. Also compute a conservative 95% confidence half-width:

4 * 1.96 * sqrt((p * (1 - p) + 1 / samples) / samples), where p = inside / samples.

Stop early when this half-width is at most tolerance. Otherwise, stop after max_samples samples. Return a dictionary containing the estimate rounded to six decimal places, the number of samples used, and whether the tolerance was reached.

Formal Specification

Implement estimate_pi(tolerance, max_samples, seed). tolerance is a positive float, max_samples is a positive integer, and seed is a nonnegative integer. The output is {"estimate": float, "samples": int, "converged": bool}.

The generator state starts at seed. Each update is state = (1664525 * state + 1013904223) mod 2^32, and each generated value is state / 2^32.

Constraints

  • 0 < tolerance <= 1
  • 1 <= max_samples <= 10^8
  • 0 <= seed < 2^32
  • The generator state is updated modulo 2^32
  • Do not store sampled points

Function Signature

def estimate_pi(tolerance, max_samples, seed):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output