Write C code that compute the value of Pi using the montecarlo method
- User
Write C code that compute the value of Pi using the montecarlo method
Assistant
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define N 100000 double get_pi_montecarlo() { int inside_circle = 0; int total_points = 0; srand(time(NULL)); for (int i = 0; i < N; i++) { double x = (double) rand() / RAND_MAX; double y = (double) rand() / RAND_MAX; if (x * x + y * y <= 1.0) { inside_circle++; } total_points++; } double pi = 4.0 * (double) inside_circle / total_points; return pi; } int main() { double pi = get_pi_montecarlo(); printf("Pi (using Monte Carlo method) = %.8f\n", pi); return 0; }This C code calculates the value of Pi using the Monte Carlo method. It generates random points within a square with side length 1 and counts the number of points that fall inside a unit circle (circle with radius 1). The ratio of the number of points inside the circle to the total number of points generates an approximation of Pi. The more points generated, the more accurate the approximation. The code defines a function that returns the calculated value of Pi and a function that calls this function and prints the result.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.