|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Help with an Incredibly Easy Problem
I'm just started taking Comp Sci. We are using the textbook Fundamentals of Java. Our teacher told us to do any two problems in one section of the book. I would choose another problem but I really want to know what I'm doing wrong. These are the specifications:
"The German mathematician Gottfried Leibniz developed the following method to approximate the value of π: π/4 = 1 - 1/3 + 1/5 - 1/7... Write a program that allows the user to specify the number of iterations used in this approximation and displays the resulting value." My code is below for reference. I know where the error is but I don't know why I'm getting it. Code:
import java.util.*;
public class PiApproximator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int iterations = input.nextInt();
double quarterPi = 1;
for(int n = 0; n < iterations; n++)
{
quarterPi -= (1 / (3 + 2*n));
quarterPi += (1 / (5 + 2*n));
System.out.println(quarterPi);
}
double pi;
pi = (quarterPi * 4);
System.out.println(pi);
}
}
When it outputs the value quarterPi, it is always 1.0. I don't know why it doesn't change. It keeps executing the for-loop but the value never changes. Nothing I change fixes it. Please help. |
|
#2
|
||||
|
||||
|
In case you never figured out the answer, I think your problem is that a lot of times JAVA casts numbers as integers, even when it seems obvious to you, the programmer, that it shouldn't. Try replacing the two lines of code that subtract and add to quarterPi, with the following (which doesn't leave anything up to JAVA's imagination)
Code:
quarterPi -= 1.0d / ( 3.0d + (double)(4.0d * n) ); quarterPi += 1.0d / ( 5.0d + (double)(4.0d * n) ); This is probably overkill, but you get the point. Adding the ".0d" to the end of an integer makes sure JAVA deals with it as a double. Also, sticking "(double)" in front of anything ensures that JAVA deals with it as a double instead of an integer. P.S. Notice that I multiplied n by 4, instead of 2. Looks like from the definition of pi you mentioned that you should do that. For example, the subtractions are: (-1/3), (-1/7), (-1/11), etc. (all are 4 more than the last). The Additions are: (1/5), (1/9), (1/13), etc. (again, all are 4 more than the last). I hope this is useful. ![]() |
|
#3
|
|||
|
|||
|
Thanks for the help. I ended up choosing a different problem because I wanted to get to bed. It's interesting to look back and see what I did wrong though although by now, I'm sure that I could have figured that out.
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Help with an Incredibly Easy Problem |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|