Question: Need help with writing a program in c language only using stdio.h and math.h (cannot use strings or arrays): Program that computes pi using a
Need help with writing a program in c language only using stdio.h and math.h (cannot use strings or arrays):
Program that computes pi using a given number of terms. The algorithm in the book for the value for pi can be determined by the series equation: "pi = 4x(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - ...), including terms up through 1/99". So, if the number of terms is 1, the result is 4. If the number of terms is 2, the result is 2.66666666666666.
In main, call your function with the number of terms set to 1, 10, 100, 1000, etc. until you have computed the approximation for 100 million terms for pi. For each value, print the number of terms, the approximation you computed, and the error from the actual value of pi using Double pi = acos(-1.0).
All printing should be done in main, with the values displayed to 14 decimal places. The function that approximates pi, only computes, do not print anything in that function.
One possible breakdown would be: write a loop in main that would increase an integer through the powers of 10. When the value reached 100million, the loop should exit. Inside that loop in main, call the function to approximate pi.
The function that calculates pi, should accept the integer number of terms to evaluate in the approximation. The function should return the result of the approximation computed as a double to be printed in main. In the computation function, another loop will execute the number of times specified by the function argument. As this loop is progressing, if the loop index is even, the current fraction should be added to the current approximation. When the loop index is odd the current fraction should be subtracted from the current approximation. The approximation will start with the value of 0 and change by each new fraction added or subtracted.
The program only needs two functions: main and ApproximatePi.
Think about the series the book indicates is needed: 1-1/3+1/5 etc. That can be written as fractions in all positions: 1/1-1/3+1/5 etc. So the loop index can be used to determine the denominator of the fraction, which will always be an odd integer. If the loop index progresses from 0 to the number of terms required by the function argument, how can those value of 0,1,2,3 be converted to 1,3,5,7... ?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
