QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 682|回复: 0

概率算法求PI的近似值

[复制链接]
发表于 2003-9-12 21:01:54 | 显示全部楼层 |阅读模式
[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]
您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-11-14 23:53 , Processed in 0.037898 second(s), 16 queries .

© 2021 Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表