Buffon投针(近似计算π)

问题定义:

如果地板的宽度是针的两倍,则向地板投针,与地板缝隙相交的概率为1/π

参考资料:

http://www.hudong.com/wiki/Buffon%E6%8A%95%E9%92%88%E9%97%AE%E9%A2%98


程序如下:

#include<stdio.h> #include<ctime> #include<cstdlib> #include <math.h> // 设地板的宽度为2,针的长度为1 void rand_seed(); float Randomf( float a, float b); int Randomi( int i, int j); int main(void) { float x1, y1, x2, y2; const int MAX= 20000000; int nCase = MAX; int k = 0; // 针与缝隙交叉的次数 double high, width; int degree; while( nCase-- ) { x1 = Randomf(2.0,100.0); y1 = Randomf(2.0,100.0); degree = Randomi( 0, RAND_MAX); high = sin( degree ); width = cos( degree ); x2 = x2 + width; y2 = y1 + high; //确定x2以后,由于两个点之间的距离是恒定的,所以y2也求出来了,但是这里y2可以去两个值,为了公平起见,交替取以过(x1,y1)的水平线以上的点,和水平线以下的点。 int min,max; if( y1 > y2 ) { min = (int)y2; max = (int)y1; } else { min = (int)y1; max = (int)y2; } if( max % 2 == 0 && min % 2 != 0) k++; } printf("%g\n", MAX * 1.0 / k ); return 0; } /** 设置随机数生成的种子 */ void rand_seed() { int seed=static_cast<int>(time(0)); srand(seed); } float Randomf( float a, float b) { int na = (int)(a * 10000); int nb = (int)(b * 10000); int temp = rand() % ( nb - na + 1 ); temp += na; return (temp / 10000.0); } int Randomi( int i, int j) { int temp; temp =( rand() % ( j - i + 1 )) + i; return temp; }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值