作者pael (就是喜歡)
看板NCTU-STAT97G
標題Re: [心得] 函數指標
時間Thu Mar 26 13:20:21 2009
※ 引述《a5170040 (Piggy)》之銘言:
: 哈~統算寫到這個部分來分享一下心得
: 因為pdf有很多
: 總不可能每個pdf都寫一個積分吧?
: (也就是底下程式碼Integral函數的內容複製好幾次)
: 這樣程式碼會變得非常長
: 所以我找了一下書並且做了實驗發現函數指標可以解決這個問題
: 所以來和大家分享一下
不錯不錯 函數指標很好用 是個蠻漂亮的技巧 ^^
我另外提供一個小小的變身版 或許會有幫助
: double p1,p2//外部變數(也就是以下的程式都可以用)
: double (*pdf)(double); //宣告函數指標 我現在只有要放x而已,所以引數只有一個
// 宣告成函數指標的陣列
double (*pdf[])(double) = {pdf_gamma, pdf_chi_square};
: //定義gamma pdf
: double pdf_gamma(double x){
: return (pow(x,p1-1.0)/g1)*pow(p2,-p1)*exp(-x/p2);//我的g1已經先積好了
: }
: //卡方pdf
: double pdf_chi_square(double x){
: return exp(-0.5*x)*pow(x,0.5*par1-1.0)/(pow(2,0.5*par1)*g1);
: }
: int main(void){
: ...
: pdf = pdf_gamma;//把要的pdf給函數指標
: //或者可以放
: //pdf = pdf_chi_square;
: Integral(); 呼叫積分函數
Integral(iType);
可以直接在 Integral(iType) 裡呼叫 pdf[iType] 來代表不同的分配
: ...
: }
: void Integral(void){
void Integral(int iType){
: for(i=0;i<分割數;i++){
: ....
: pdf(x1)+pdf(x2);//這邊就可以用函數指標作運算了
pdf[iType](x1)+pdf[iType](x2);
: ....
: }
: }
: 大致上這樣
: 哈
--
──│ - Le@p - my way , my dream ..
│ ╭─│ ╭─│
│ ╭─│ ──╯ ┌─╯ Th
e l
im
pi
d k
it
e b
eg
an
to
fl
y
──┘ ┌─╯ ┘
──╯ I wanna be a sky , in my mind ..
→ [email protected] ←
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.114.200
1F:推 a5170040:大推!!! 03/26 19:59
2F:推 hiloin:超級推!!! 03/26 20:28
3F:推 teddd:有看有推... 03/27 19:07