作者td00414955 (banana)
站內C_and_CPP
標題[問題] 估計pi...
時間Sat Apr 9 01:20:12 2011
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
C++
問題(Question):
只能跑到4316個數
餵入的資料(Input):
10000
程式碼(Code):(請善用置底文網頁, 記得排版)
#include "stdafx.h"
#include "iostream"
using namespace std;
int s(int a);
double squ(double b);
int _tmain(int argc, _TCHAR* argv[])
{
int n,count=0;
double u1,u2;
cout <<"現在要來估計pi" <<endl;
cout <<"請輸入要用多少點來估計" <<endl;
cin >>n;
for(int i=1;i<=n;i++)
{
u1=double(s(i))/2147483647;
u2=double(s(i))/2147484000;
cout <<"第" <<i <<"個u1=" <<u1 <<"\tu2=" <<u2<<endl;
if(squ(2*u1-1)+squ(2*u2-1)<1)
{
++count;
}
}
cout <<"落在圓內的數有" <<count <<"個" <<endl;
cout <<"估計出來的pi為:" <<4.0*count/n <<endl;
return 0;
}
int s(int a)
{
int s0=100000000,s1;
if(a==1)
{
return (16807*s0)%2147483647;
}
else
{
s1=(16807*s(a-1))%2147483647;
if(s1<0)
{
s1=s1+2147483647;
}
return s1;
}
}
double squ(double b)
{
return b*b;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 60.248.22.40
→ tropical72:為何亂數要自己寫?特殊需求嗎? 04/09 01:28
→ TsinTa:這亂數產生法的邏輯是什麼阿,你每次的u1和u2都一樣... 04/09 01:33
→ tropical72:(16807*s0)%2147483647; 這會有問題,前半段就 OV 了 04/09 01:36
→ tropical72:我想問這段程式碼重點到底是蒙地卡羅法求pi還是寫亂數? 04/09 01:38
→ tropical72:我好像看到重點了..那個亂數是用 recursive 寫的, 04/09 01:44
→ tropical72:最後應是 stack ov 吧 04/09 01:44
→ TsinTa:我不太懂這亂數的邏輯,因為a只要固定,產生的值就會一樣。 04/09 01:54
→ DrStein:但a不會固定啊 a隨 i跑哩 04/09 02:59