C language learning in different ways to calculate pi

Source: Internet
Author: User



/***************************************************
function
* Calculate pi by probability method and cutting method
Description
* Probability method requires a number of points not in the input circle
* The number of cuts required for the cutting method
***************************************************/


#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>

/* Probability method calculates pi */
int Probability_calculate_pi ()
{
int i,n,sum=0;
Double x, y;

printf ("Please input point count\n");//number of input points
scanf ("%d", &n);

Srand (Time (NULL));
for (i=0;i<n;i++)
{
x = (double) rand ()/rand_max; Generates a random number of 0~1 X
y = (double) rand ()/rand_max; Generates a random number of 0~1 y

if ((X*x + y*y) <=1)
{
sum++;
}
}
printf ("pi=%f\n", (double) 4*sum/n);
return 0;
}

/* Calculate pi */by cutting round
int Cyclotomic_calculate_pi ()
{
int i,n,s;
Double k,y2;

printf ("Please input incision count\n");//Input cut times
scanf ("%d", &n);

i = 0;
k = 3.0;
y2 = 1.0;

s = 6;
while (I<n)
{
printf ("The%dth incision,is%d, pi=%.24f\n", I,s,k*sqrt (y2));
s*=2;
y2 = 2-sqrt (4-y2);
i++;
k*=2.0;
}
return 0;
}

int main (int argc,char *argv[])
{
Probability_calculate_pi ();
Cyclotomic_calculate_pi ();
return 0;
}


The results of the operation are as follows:

C language learning in different ways to calculate pi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.