[問題] 估計pi...

看板C_and_CPP作者 (banana)時間13年前 (2011/04/09 01:20), 編輯推噓0(009)
留言9則, 4人參與, 最新討論串1/2 (看更多)
開發平台(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

04/09 01:28, , 1F
為何亂數要自己寫?特殊需求嗎?
04/09 01:28, 1F

04/09 01:33, , 2F
這亂數產生法的邏輯是什麼阿,你每次的u1和u2都一樣...
04/09 01:33, 2F

04/09 01:36, , 3F
(16807*s0)%2147483647; 這會有問題,前半段就 OV 了
04/09 01:36, 3F

04/09 01:38, , 4F
我想問這段程式碼重點到底是蒙地卡羅法求pi還是寫亂數?
04/09 01:38, 4F

04/09 01:44, , 5F
我好像看到重點了..那個亂數是用 recursive 寫的,
04/09 01:44, 5F

04/09 01:44, , 6F
最後應是 stack ov 吧
04/09 01:44, 6F

04/09 01:54, , 7F
我不太懂這亂數的邏輯,因為a只要固定,產生的值就會一樣。
04/09 01:54, 7F

04/09 02:59, , 8F
但a不會固定啊 a隨 i跑哩
04/09 02:59, 8F
文章代碼(AID): #1DdqFEye (C_and_CPP)
文章代碼(AID): #1DdqFEye (C_and_CPP)