This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am coding this simple pi calculator for my Java class as a part of us learning about basic loops and it seems like everything is OK except the values printed for pi is infinity when it should be 3.14...something according to the number of iterations. I read that this could be maybe related to a double variable dividing by 0 and it's giving a weird infinity output instead of a normal Java runtime exception?
Here's my code:
package lab05;
public class Lab05 {
public static void main(String[] args) {
// Variable declarations
double pie = 3;
double savepie = 0;
double term = 0;
double savei = 0;
double sign = 1;
boolean isRangeFound = false;
int i;
// For loop
for (i=0; i <= 1000;) { // Only up to 1000 iterations before loop must end.
term = (sign * 4) / ((2*i) * (2*i+1) * (2*i+2));
pie = pie + term;
sign = (-1 * sign);
if (isRangeFound==false && (pie >=3.14159265 & pie < 3.14159266)) {
savepie = pie;
savei = i;
isRangeFound = true;
}
if (i == 200||i == 500||i == 1000) {
System.out.print("The value of \u03C0 is: ");
System.out.printf("%.10f",pie);
System.out.print(" when i = " + i);
System.out.println(" ");
}
i++;
}
// Final output statement
System.out.println ("The number of iterations to get to 3.14159265 is " + savei + ".");
System.out.printf("\n\u03C0 = %.10f",savepie);
System.out.println(" ");
}
}
Here's my output in Netbeans:
The value of π is: Infinity when i = 200
The value of π is: Infinity when i = 500
The value of π is: Infinity when i = 1000
The number of iterations to get to 3.14159265 is 0.0.
π = 0.0000000000
BUILD SUCCESSFUL (total time: 0 seconds)
Here's the link to the instructions that I should follow with a Visual Logic flowchart that I tried to follow to the T. Thanks.
https://www.dropbox.com/s/2m26a32afedk9yu/Lab05%20Assignment%281%29.pdf?dl=0
You need to start your loop when i=1? The way you have it, when i=0, then term will be infinity (due to the divide-by-zero), and so pie will be infinity as well.
Related
The assignment is
The following method can be used to approximate the value of Pi:
Pi/4 = 1 – (1/3) + (1/5) – (1/7) + (1/9) – (1/11) + …
Write a program that allows the user to specify the number of iterations used in this approximation and display the approximated value of Pi. Test the program for small, medium and large number of iterations.
It compiles but it not giving me the answers I want. For instance when I put in 1, it gives me 1/3 instead of 8/3. When I pretty much any other number, it just bugs out and I can't get any output.
import java.util.*;
import java.io.*;
public class LabFiveUnitFour {
public static void main(String[] args) {
double n, pi=1, count=1, amount;
Scanner input = new Scanner(System.in);
System.out.println("How many pi iterations do you want?");
amount = input.nextDouble();
n = amount;
do {
pi = ((Math.pow(-1, n)) / (2 * n + 1));
} while (!(count == amount));
{
n = n - 1;
pi = pi + ((Math.pow(-1, n)) / (2 * n + 1));
count++;
}
pi = 4 * (1 - pi);
System.out.println(pi + "");
}
}
You have a do/while loop that is controlled by comparing count and amount and the body of that loop is not doing anything to modify either of those variables. The result will be that the loop will never exit.
I'm having trouble with this program, we are supposed to compute pi to six significant figures, WITHOUT ROUNDING and WITHOUT using math library constant, the program should also show the number of iterations it took to reach 6 sig fig accuracy as well as the math constant in the output, so far I'm just trying to get my head around computing pi, I'm completely lost on how to get six 6 figs with or without rounding, not to mention how to iterate how many iterations it took to reach 6 sig figs pls help.
"Write an algorithm and program to compute π, using the formula described in the text PI/4 =1-(1/3)+(1/5)-(1/7)+(1/9)...." Output will include your computed value for π, the math library constant expected value for π and the number of iterations it took to reach six-significant digit accuracy. The number of iterations could exceed 250,000. Make your output clean and easy to read for comparing results.
This is the code I have so far to compute pi but even this I'm not sure is right.
public static void main(String[] args) throws Exception {
Double pi=1.0;
int s=1;
for (double j=3.0; j<100.0; j=j+2)
{
if (s % 2 == 0)
pi = pi + (1/j);
else
pi = pi - (1/j);
s = s + 1;
}
System.out.println(4*pi);
So there is presumably a way to make an a priori estimate of error using the alternating series theorem. But suppose you do not know the theorem or trust your math (if you do, just change 100.0 above to the right number. 800000.0 as estimated above would work, just barely). Here is something a little safer, perhaps, though it might be better to check the goodness of the estimate only every 1000 times through the loop, not each time?
Double pi=1.0; Boolean closeEnough=false;
int s=1;
for (double j=3.0; (!closeEnough); j=j+2)
{
if (s % 2 == 0)
pi = pi + (1/j);
else
pi = pi - (1/j);
if (Math.abs(4/(j+2))<0.000005)
closeEnough=true;
s = s + 1;
}
Ideally you should encapsulate your calculation in a class:
public class PI {
private double estimate = 1.0;
private int iteration = 0;
public double getEstimate() {
return 4 * estimate;
}
public void iterate() {
double ratio = 1.0 / (iteration * 2 + 3);
if (iteration % 2 == 0)
estimate -= ratio;
else
estimate += ratio;
iteration++;
}
}
Then the loop becomes pretty trivial:
PI pi = new PI();
while (Math.round(pi.getEstimate() * 1e5) != Math.round(Math.PI * 1e5))
pi.iterate();
For me this took 130,657 iterations
consider
String piStr = "3.14159";
Double pi=1.0;
int s=1;
double j=3.0;
String lcl = "";
String upToNCharacters = "";
while (true)
{
if (s % 2 == 0)
pi = pi + (1/j);
else
pi = pi - (1/j);
s = s + 1;
j=j+2;
lcl = "" + 4 * pi;
upToNCharacters = lcl.substring(0, Math.min(lcl.length(), 7));
if (upToNCharacters.equals(piStr)) {
break;
}
}
System.out.println(upToNCharacters);
System.out.println("after " + s);
output
3.14159
after 136121
My program is supposed to run a formula and print out the end product when a counter reaches 100,200,500,and when a variable hits a certain value. Currently it prints out
Exception in thread "main" java.lang.ArithmeticException: / by zero
Which I understand is because before the counter takes effect and bumps up the variable it attempts to divide by zero which causes that. When I do change the variable it stops at 100 and prints out "The value of π at 100 is: 0.0".
Here's the code:
int i = 1;
int counter = 0;
double pi = 4/((2*i)*(2*i+1)*(2*i+2));
while(counter <= 100 ){
i++;
counter ++;
if(i==100){
System.out.println("The value of \u03C0 at 100 is: "+ pi);
}
if (i==200){
System.out.println("The value of \u03C0 at 200 is: " +pi);
}
if (i==500){
System.out.println("The value of \u03C0 at 500 is:"+pi);
}
if(pi==3.14159 ){
System.out.println("The number of iterations to get to 3.14159 is "+counter+". \u03C0 = 3.141599074");
}
}
Your logic has some problems. Have you followed your code through with a debugger? If you look at your code,
int i = 1;
int counter = 0;
double pi = 4/((2*i)*(2*i+1)*(2*i+2));
happens once, before the while loop actually changes i. Move pi into the while loop to update pi with a new i. Debuggers are your friend.
Another place where a debugger would be your friend would be in the while loop proper. Follow that through and see what happens when your logic approaches your testing conditionals. Your first excitement I predict will be around counter = 99 and the next couple of loops through, or not :)
You might want to consider some if-else blocks for your multiple tests, or you could also use a switch statement for your counter tests.
Try
...
for (counter = 1; counter <= 500; counter++, i++) {
double pi = (double) 4/((2*i)*(2*i+1)*(2*i+2));
if (counter % 100 == 0) {
System.out.println("The value of \u03C0 at " + counter + " is: "+ pi);
}
if(pi == 3.14159 ){
System.out.println("The number of iterations to get to 3.14159 is "+counter+". \u03C0 = 3.141599074");
}
}
http://projecteuler.net/problem=1
Hey. I'm a high schooler trying to get a good grasp on programming problems, so I visited Project Euler. For Problem 1, I wrote up some code in Java that would of solved it, but something is evidently going wrong. Can I get some insight as to what?
Explanation:
I stop everything at the index value of 332 because Java counts from 0, and 333 * 3 is 999 which is below 1,000. Apples is a seperate class with pretty much the same code, although it counts for 5. At the end, I manually add together the two answers, but it wasn't right. What am I doing wrong?
The two final sums are:
Three: 164838
Five: 97515
public class Learning {
public static void main(String[] args){
int three[] = new int[333];
int counter = 0;
three[332] = 0;
int totalthree = 0;
int threeincrementer = 1;
int grandtotal;
boolean run = true;
boolean runagain = true;
for (counter = 1; counter<=332; counter++){
three[counter] = 3 * counter;
if (!(three[332] == 0)){
System.out.println("Finished three.");
while (run == true){
totalthree = totalthree + three[threeincrementer];
threeincrementer++;
if (threeincrementer >= 332){
run = false;
System.out.println("Three final is: " + totalthree);
}
}
}
if (runagain == true){
apples ApplesObject = new apples();
ApplesObject.rerun(0);
runagain = false;
}
}
}
}
Some numbers are at the same time multiplication of 3 AND 5 like 15 so you shouldn't separately calculate sum of all multiplications of 3 and multiplications of 5 and than add them because you will end up doing something like
sum3 = 3,6,9,12,15,...
sum5 = 5,10,15,...
so first sum3 will include 15, and sum5 will also include it which means you will add 15 two times. Now to balance your calculations you will need to subtract from your sum3+sum5 sum which will add all multiplications of 15
sum15 = 15,30,45,...
So using your approach your final formula should look like sum3+sum5-sum15.
But simpler solution for this problem can look like
sum = 0
for each X in 1...999
if (X is multiplication of 3) OR (X is multiplication of 5)
add X to sum
To check if some number X is multiplication of number Y you can use modulo operator % (example reminder = X % Y) which finds the remainder of division of one number by another.
You can find more Java operators here
I am new to java, and my program is likely nowhere near as efficient as it could be, but here it is:
public class Compute {
public static void main(String[] args) {
for(double i = 10000; i <= 100000; i += 10000)
{
System.out.println("The value for the series when i = " + i + " is " + e(i));
}
}
public static double e(double input) {
double e = 0;
for(double i = 0; i <= input; i++)
{
e += 1 / factorial(input);
}
return e;
}
public static double factorial(double input) {
double factorial = 1;
for(int i = 1; i <= input; i++)
{
factorial *= i;
}
return factorial;
}
}
I believe this calculates the value e for i = 10000, 20000, ..., & 100000.
Where e = 1 + (1/1!) + (2/2!) + ... + (1/i!)
It takes about 47 seconds to do so, but I believe it works.
My issue is, for every i, the result is always 0.0
I believe this is because whenever the method factorial is called, the return value is too big to be stored which somehow causes a problem.
What can I do to store the value returned by the method Factorial?
Although you can calculate arbitrary precision results with BigDecimal, there is no need to calculate to 100000! for the series expansion of e. Consider that the 20th term in the series (20/20!) has a magnitude of about 10-19, so its contribution to the overall total is insignificant.
In other words, the contribution of any terms after the 20th would change only digits after the 19th decimal place.
You should probably use java.math.BigInteger to store the factorial.
Change this
e += 1 / factorial(input);
to
e += 1 / factorial(i);
Lots to do to speed up the code. Think about (i+1)! vs i!, don't recalc the whole factorial every time.
Also stop calculating when the answer will change less than the required precision like Jim said.