I'm taking my first Java programming class and this is my first class project. I'm so confused about how to approach it. Any help or correction will be appreciated.
You can approximate the value of the constant PI by using the following series:
PI = 4 ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... + ( (-1)^(i+1) )/ (2i - 1) )
Prompt the user for the value of i (in other words, how many terms in this series to use) to calculate PI. For example, if the user enters 10000, sum the first 10,000 elements of the series and then display the result.
In addition to displaying the final result (your final approximation of PI), I want you to display along the way your intermediate calculates at every power of 10. So 10, 100, 1000, 10000 and so on, display to the screen the approximation of PI at that number of summed elements.
This is what i did so far ..
import java.util.Scanner;
public class CalculatePI {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner (System.in);
// Prompt the user to enter input
System.out.println("Enter number of terms");
double i = input.nextDouble(); // value of i user entered
double sum = 0;
for(i=0; i<10000; i++){
if(i%2 == 0) // if the remainder of `i/2` is 0
sum += -1 / ( 2 * i - 1);
else
sum += 1 / (2 * i - 1);
}
System.out.println(sum);
}
}
First thing I see is you attempting to return a value from your void main
method.
don't return pi;
from your main method. Print it.
System.out.println(pi);
Secondly, when people write a for
loop, they're commonly iterating over i
, which is probably the same i
that your professor referred to in the formula
for(double i=0; i<SomeNumber; i++)
{
sum += ((-1)^(i+1)) / (2 * i - 1) );
}
now, that won't work correctly as is, you still have to handle the ^
, which java doesn't use natively. luckily for you, -1^(i+1)
is an alternating number, so you can just use an if
statement
for(double i=0; i<SomeNumber; i++)
{
if(i%2 == 0) // if the remainder of `i/2` is 0
sum += -1 / ( 2 * i - 1);
else
sum += 1 / (2 * i - 1);
}
sometimes the answer is a simple line of code. Also you are reassigning i to 0 so Im assuming you are using the user input in the wrong way.
for(int counter=1;counter<input;counter++){
sum += Math.pow(-1,counter + 1)/((2*counter) - 1);
}
for input that should can be any variable, hard coded or set by user input (such as 1000, 10000, 100000). This should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With