[C Language] Use Leibniz’s formula π/4≈1−1/3+1/5−1/7+⋯ to find the approximate value of π

analyse problem

This problem is an iterative solution process using loops. Similar to the cumulative summation discussed before, the value of the latter item is the value of the previous item + a regular number, expressed as s=s+i. As long as we analyze the rules of the data that need to be added, this problem will be solved. Let's analyze the rule (1). The numerator of each item is 1. (2) The denominator of the latter term is the denominator of the previous term plus 2. (3) The sign of the first term is positive, and from the second term onwards, the sign of each term is opposite to the sign of the previous term.

To complete the analysis, there is also a condition for ending the loop. This is to find an approximation. Let's determine whether the absolute value of the loop ending condition i is greater than or equal to 10-6. Here we need to use the function fabs() to find the absolute value. Add the #include<math.h> header file at the head of the program.

Sorting out ideas

Variables and initial values : double s=0, i=1.0; int n=1, sign=1;

loop body

  • s=s+i
  • i: consists of symbol, numerator and denominator,
  • Symbol: sign=-sign;
  • Numerator: 1
  • Denominator: 1, 3, 5, 7, 9... Rule: n=n+2,2*n-1;
  • i=sign*1.0/n;

Loop condition : |i|The absolute value is less than 10 raised to the power of -5 -----while(fabs(i)>=1e-5)

  • 10 to the power of -5 is expressed in scientific notation as 1e-5
  • #include<math.h> 

Draw a flow chart ( make appropriate adjustments to variables )

sign=1, pi=0, n=1, term=1

When |term|≥10-6

pi=pi+term

n=n+2

sign=-sign

term=sign/n

pi=pi*4

Output pi

Programming

#include<stdio.h>
#include<math.h>
int main()
{
	int sign=1;
	double item=1,pi=0,n=1;
	
	while(fabs(item)>=1e-6)
	{
		pi=pi+item;
		n=n+2;
		sign=-sign;
		item=sign/n;				
	}
	pi=4*pi;
	printf("pi=%f",pi);
	return 0;
 } 

operation result

 think

  • What adjustments need to be made to improve the accuracy of pi?
  • Can you suggest other solutions to the problem?

Guess you like

Origin blog.csdn.net/studyup05/article/details/130375039