The loop would terminate if the two sums were subtracted, and produced a difference of 0.0000009 or less (7 significant figure accuracy). One with n+1 iterations, the other with n iterations. The bigger the number, the closer the calculation gets to PI. Perhaps having a for loop inside a for loop would work better. Tools Required: For C/C++: A C++ compiler that is OpenMP capable (e.g. This program asks the user to input a number on to how many times there has to be a calculation to PI. Is this a good approach, or is it horribly inefficient? How might I improve it? This is done by setting float variables and creating a while loop that performs calculations in. One way to calculate it can be given using Nilkantha’s series. We commonly know Pi 3.14 or Pi 22/7, but it is just an approximation for our ease. ("The number of iterations needed to reach " + "seven-significant digit accuracy is: " + counter) // Uses the Leibniz formula with floats to calculate pi. Practice Pi is an irrational number having non-recurring decimal values. ("The library constant value of pi is: " + Math.PI) ("My computed value of pi is: " + sum * DENOMINATOR_CANCEL) At the end of the first while loop, a question is shown to the user if he wants to continue. If (delta < SMALLEST_DELTA) // If delta reaches 7-sig accuracy This program asks the user to input a number on to how many times there has to be a calculation to PI. Here is the code I came up with to do that: public class ComputePIįinal double SMALLEST_DELTA = 0.0000004535899 įor (int j = 1 j < LARGE_NUMBER j += 2) // Computes number close to piĭouble firstFrac = (1.0 / (j * 2.0 - 1.0)) ĭouble secondFrac = (1.0 / (j * 2.0 + 1.0)) įor (int i = 1 (!closeEnough) i += 2) //"My computed value of pi"ĭouble firstNum = (1.0 / (i * 2.0 - 1.0)) ĭouble secondNum = (1.0 / (i * 2.0 + 1.0)) ĭelta = sumOne * DENOMINATOR_CANCEL - sum * DENOMINATOR_CANCEL The more precision you want, the more loop iterations you will need. I need to calculate pi to 7 significant figures in Java- without using Math.PI. To calculate pi with 10 decimal digits of precision the loop is executed 8 times.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |