请写一个用概率计算圆周率的程序,用python语言,java语言,C++语言分别写一下,谢谢你
时间: 2024-02-15 21:02:16 浏览: 76
使用python计算圆周率
5星 · 资源好评率100%
Python代码实现:
```python
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle / num_point_total
print(estimate_pi(10000))
```
Java代码实现:
```java
import java.util.Random;
public class EstimatePi {
public static double estimatePi(int n) {
int numPointCircle = 0;
int numPointTotal = 0;
Random rand = new Random();
for (int i = 0; i < n; i++) {
double x = rand.nextDouble();
double y = rand.nextDouble();
double distance = x * x + y * y;
if (distance <= 1) {
numPointCircle++;
}
numPointTotal++;
}
return 4.0 * numPointCircle / numPointTotal;
}
public static void main(String[] args) {
System.out.println(estimatePi(10000));
}
}
```
C++代码实现:
```c++
#include <iostream>
#include <random>
double estimate_pi(int n) {
int num_point_circle = 0;
int num_point_total = 0;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> dis(0.0, 1.0);
for (int i = 0; i < n; i++) {
double x = dis(gen);
double y = dis(gen);
double distance = x * x + y * y;
if (distance <= 1) {
num_point_circle++;
}
num_point_total++;
}
return 4.0 * num_point_circle / num_point_total;
}
int main() {
std::cout << estimate_pi(10000) << std::endl;
return 0;
}
```
阅读全文