日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux多线程计算pi,使用蒙特卡洛方法多线程计算pi值

發(fā)布時間:2024/1/23 linux 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux多线程计算pi,使用蒙特卡洛方法多线程计算pi值 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我正在嘗試使用montecarlo方法和使用并行C代碼來查找PI的值。我已經(jīng)寫了serail代碼并且工作正常。但是,并行代碼給我一些時間0或PI錯誤的值負(fù)值使用蒙特卡洛方法多線程計算pi值

我的代碼

#include

#include

#include

#include

#define NUM_THREADS 4 //number of threads

#define TOT_COUNT 10000055 //total number of iterations

void *doCalcs(void *threadid)

{

long longTid;

longTid = (long)threadid;

int tid = (int)longTid; //obtain the integer value of thread id

//using malloc for the return variable in order make

//sure that it is not destroyed once the thread call is finished

float *in_count = (float *)malloc(sizeof(float));

*in_count=0;

unsigned int rand_state = rand();

//get the total number of iterations for a thread

float tot_iterations= TOT_COUNT/NUM_THREADS;

int counter=0;

//calculation

for(counter=0;counter

//float x = (double)random()/RAND_MAX;

//float y = (double)random()/RAND_MAX;

//float result = sqrt((x*x) + (y*y));

double x = rand_r(&rand_state)/((double)RAND_MAX + 1) * 2.0 - 1.0;

double y = rand_r(&rand_state)/((double)RAND_MAX + 1) * 2.0 - 1.0;

float result = sqrt((x*x) + (y*y));

if(result<1){

*in_count+=1; //check if the generated value is inside a unit circle

}

}

//get the remaining iterations calculated by thread 0

if(tid==0){

float remainder = TOT_COUNT%NUM_THREADS;

for(counter=0;counter

float x = (double)random()/RAND_MAX;

float y = (double)random()/RAND_MAX;

float result = sqrt((x*x) + (y*y));

if(result<1){

*in_count+=1; //check if the generated value is inside a unit circle

}

}

}

}

int main(int argc, char *argv[])

{

pthread_t threads[NUM_THREADS];

int rc;

long t;

void *status;

float tot_in=0;

for(t=0;t

rc = pthread_create(&threads[t], NULL, doCalcs, (void *)t);

if (rc){

printf("ERROR; return code from pthread_create() is %d\n", rc);

exit(-1);

}

}

//join the threads

for(t=0;t

pthread_join(threads[t], &status);

//printf("Return from thread %ld is : %f\n",t, *(float*)status);

tot_in+=*(float*)status; //keep track of the total in count

}

printf("Value for PI is %f \n",1, 4*(tot_in/TOT_COUNT));

/* Last thing that main() should do */

pthread_exit(NULL);

}

+0

該代碼中有許多可疑的事情,比如為什么你為'in_count'動態(tài)地分配一個浮點(diǎn)數(shù)?你順便把它看作一個整數(shù)。哦,而且你并沒有在任何地方釋放導(dǎo)致內(nèi)存泄漏的配置。 –

+0

我建議使用'double'。如果你想'浮動',為什么不計算'22/7'或'355/113'? –

+0

@WeatherVane他想嘗試蒙特卡洛方法,我認(rèn)為教育。 –

總結(jié)

以上是生活随笔為你收集整理的linux多线程计算pi,使用蒙特卡洛方法多线程计算pi值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。