高中数学课本上曾经写过用计算机算得pi的近似值,用的是蒙特卡里方法。但是那时的我还不知道编程为何物,今天突然又想到这个问题,尝试了一下,发现并不是那么难,用C语言和python各实现了一遍。
不多说上代码。
c语言实现
#include
#include
#include
#include
#define MAXN 1200000//总随机点数,这个数值越大,pi值计算的越精确,相应的耗费更多的时间
int main(void)
{
int i=0;
double count=0.0;
double x=0.0,y=0.0,dist=0.0;
double my_pi=0;
srand((unsigned)time(NULL));
//随机数种子被初始化
clock_t start = clock();//时间起点
for(i=0;i
{
x = ((double)rand()/RAND_MAX);//生成0-1的随机数
y = ((double)rand()/RAND_MAX);
dist = sqrt(x*x + y*y);//计算(x,y)到原点的距离
if(dist <= 1.0)
count++;//记录落在半圆内的随机点的个数
}
my_pi = 4*(count/MAXN);
clock_t finish = clock();//函数运行结束时间记录
printf("%lf\n",my_pi);
double duration = (double)(finish - start) / CLOCKS_PER_SEC;//计算出函数所耗费的时间
printf("It costs %lf s",duration);
return 0;
}
python版 python版本为3.5X
# -*- coding:utf-8 -*-
from random import random
from math import sqrt
from time import clock
MAXN = 120000
count =0
clock()
for i in range (1,MAXN):
x, y = random(),random()
dist = sqrt(x**2+y**2)
if dist <= 1.0:
count = count + 1
pi = 4*(count/MAXN)
print("PI的值为") % pi
print("程序的运行时间是%-5.5ss") % clock()
pi.PNG
看的出来计算出的pi值离精确的pi值还有一定距离,并且数值会波动,毕竟这是用概率去模拟的,样本点足够多,才可能精确不是?
第一次使用Markdown写东西,将就看吧o(╯□╰)o
┴┬┴┬/ ̄\_/ ̄\
┬┴┬┴▏ ▏▔▔▔▔\
┴┬┴/\ / ﹨
┬┴∕ / )
┴┬▏ ● ▏
┬┴▏ ▔█
┴◢██◣ \___/
┬█████◣ /
┴█████████████◣
◢██████████████▆▄
█◤◢██◣◥█████████◤\
◥◢████ ████████◤ \
┴█████ ██████◤ ﹨
┬│ │█████◤ ▏
┴│ │ ▏
┬ ∕ ∕ /▔▔▔\ ∕
┴/___/﹨ ∕ ﹨ /\
┬┴┬┴┬┴\ \ ﹨/ ﹨
┴┬┴┬┴┬┴ \___\ ﹨/▔\﹨ ▔\
▲△▲▲╓╥╥╥╥╥╥╥╥\ ∕ /▔﹨/▔﹨
**╠╬╬╬╬╬╬╬╬*﹨ / //