|
发表于 2023-7-30 12:35:02
|
显示全部楼层
要用Python或C++求π(PI),不依赖于现有的模块,可以使用著名的蒙特卡洛方法来近似计算π的值。以下是使用Python和C++编写的示例代码:
Python代码:
- import random
- def estimate_pi(num_points):
- points_inside_circle = 0
- points_total = num_points
- for _ in range(num_points):
- x = random.uniform(0, 1)
- y = random.uniform(0, 1)
- distance = x**2 + y**2
- if distance <= 1:
- points_inside_circle += 1
- pi_estimate = 4 * points_inside_circle / points_total
- return pi_estimate
- num_points = 1000000
- estimated_pi = estimate_pi(num_points)
- print("估算的π值为:", estimated_pi)
复制代码
C++代码:
- #include <iostream>
- #include <random>
- double estimatePi(int numPoints) {
- int pointsInsideCircle = 0;
- int pointsTotal = numPoints;
- std::random_device rd;
- std::mt19937 gen(rd());
- std::uniform_real_distribution<double> dis(0.0, 1.0);
- for (int i = 0; i < numPoints; i++) {
- double x = dis(gen);
- double y = dis(gen);
- double distance = x * x + y * y;
- if (distance <= 1.0) {
- pointsInsideCircle++;
- }
- }
- double piEstimate = 4.0 * pointsInsideCircle / pointsTotal;
- return piEstimate;
- }
- int main() {
- int numPoints = 1000000;
- double estimatedPi = estimatePi(numPoints);
- std::cout << "估算的π值为:" << estimatedPi << std::endl;
- return 0;
- }
复制代码
这些代码使用蒙特卡洛方法生成随机点,并计算落在单位圆内的点的比例。通过将该比例乘以4,可以得到对π的近似估计。请注意,这种方法是一种概率性的近似,所以计算结果可能不够精确。增加num_points(Python)或numPoints(C++)的值可以提高估计的准确性。
如果问题已经解决,请设置最佳答案 |
|