|
[code:1]
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
//产生0到1之间的随机数
inline long double randf();
//概率算法求积分
long double HiborMiss(long double (*f) (long double),
unsigned long n);
//要积分的函数
long double f(long double x);
////////////////////////////////////////////////////
inline long double randf()
{
return rand()/(long double)(RAND_MAX);
}
long double HiborMiss(long double (*f) (long double),
unsigned long n)
{
unsigned long k=0;
unsigned long i;
for(i=0;i<n;i++)
{
long double x = randf();
//printf("x=%f",(double)x);
long double y = randf();
//printf("y=%f",(double)y);
if(!(y>(*f)(x))) k++;
}
printf("k=%lu\nn=%lu\n",k,n);
return 4*k/(long double)n;
}
long double f(long double x)
{
return (long double)(sqrtl(1-x*x));
}
int main(int argc, char *argv[])
{
long double (*p) (long double);
p=f;
srand((unsigned)(time(NULL)/2));
printf("%1.10f\n",(double)HiborMiss(p,100000000));
//100000000为迭代次数。
system("PAUSE");
return 0;
}
[/code:1] |
|