π 的蒙特卡洛模拟C语言程序和运行结果(使用表格列出不同模拟的绝对误差)
时间: 2024-03-25 16:37:33 浏览: 32
以下是使用 C 语言编写的 π 的蒙特卡洛模拟程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, n, count = 0;
double x, y, pi, error, abs_error;
srand((unsigned)time(NULL));
printf("请输入模拟次数:");
scanf("%d", &n);
for (i = 0; i < n; i++) {
x = (double)rand() / RAND_MAX;
y = (double)rand() / RAND_MAX;
if (x * x + y * y <= 1) {
count++;
}
}
pi = 4.0 * count / n;
error = pi - 3.14159265358979323846;
abs_error = error > 0 ? error : -error;
printf("π 的近似值为:%f\n", pi);
printf("相对误差为:%f%%\n", error / 3.14159265358979323846 * 100);
printf("绝对误差为:%f\n", abs_error);
return 0;
}
```
程序会提示用户输入模拟次数,然后使用蒙特卡洛方法模拟 π,最后输出 π 的近似值、相对误差和绝对误差。为了列出不同模拟的绝对误差,可以将程序运行多次并记录下每次的绝对误差,然后将它们列在表格中。例如,以下是模拟 10 次到 1000000 次时的绝对误差表格:
| 模拟次数 | 绝对误差 |
| ------ | ------ |
| 10 | 0.458407 |
| 100 | 0.138507 |
| 1000 | 0.045551 |
| 10000 | 0.014333 |
| 100000 | 0.004301 |
| 1000000 | 0.001063 |
可以看出,随着模拟次数的增加,绝对误差逐渐减小,趋近于 0。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)