Question
Can someone help fix my code? I am trying to calculate Pi with a for Loop in Java. This is my code and my output.
Can someone help fix my code? I am trying to calculate Pi with a for Loop in Java. This is my code and my output.
public class PiLooping {
public static void main(String[] args) {
// Declare and initialize piAppx
double piAppx = 1.0 - 1.0 / 3.0 + 1.0 / 5.0;
// What is the max value for i
// Use 407 in the first run, then use 100000000
int MAX_I_VALUE = 407;
// set variable for mulitplying to find piAppx
double s = 7.0 ;
for (int i = 0; i <= MAX_I_VALUE; i++) {
double piComponent = ( (1.0 / s) + (1.0 / (s + 2.0)) ) ;
piAppx = piAppx - piComponent ;
s = s + 2.0 ;
}
double finalPi = 4.0 * piAppx;
// Output the approximation you computed for Pi
System.out.println("Pi approximation =\t" + finalPi);
// Output the Math library value of Pi
System.out.println("Math.PI =\t\t" + Math.PI);
// Output the difference between Math.PI and the approximation
// for Pi that you computed
System.out.println("Math.PI - piAppx =\t" + (Math.PI - finalPi));
}
}
Output:
Pi approximation = -15.628512311276912
Math.PI = 3.141592653589793
Math.PI - piAppx = 18.770104964866704
Desired Output=
Pi approximation = 3.1464706733524115
Math.PI = 3.141592653589793
Math.PI - piAppx = -0.0048780197626183686
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started