Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Database Foundations Technology Fundamentals For IT Success

Authors: Bob Bryla

1st Edition

0782143725, 9780782143720

More Books

Students also viewed these Databases questions