Write Python code that uses Monte Carlo simulation to estimate the value of pi.
- User
Write Python code that uses Monte Carlo simulation to estimate the value of pi.
- Assistant
Providing Monte Carlo Code
The user wants Python code for a simple Monte Carlo method to estimate pi. Since they didn't request an explanation, I’ll keep my response focused on providing concise code. I should propose generating N random points in a unit square and then counting how many fall inside a quarter circle. I can include both a pure Python example and a vectorized version using NumPy, but I need to keep it brief. I’ll make sure the code is presented clearly in a text block. ```python import random import math
def estimate_pi(num_samples: int = 1_000_000) -> float: inside_circle = 0
for _ in range(num_samples): x = random.random() # uniform in [0, 1) y = random.random() # Distance from (0,0) if x*x + y*y <= 1.0: inside_circle += 1 # Points in quarter-circle / total points ≈ π/4 return 4.0 * inside_circle / num_samplesif name == "main": est = estimate_pi(1_000_00) # adjust for speed/accuracy print("Estimated π:", est) print("Error:", abs(math.pi - est))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.