StarCoder
StarCoder

Reputation: 251

How to use double in a for loop rather than an int?

I am wondering how to make a for loop use a double variable, instead of an int. What I've tried, only produced a double, but it was basically an int with a ".0" behind each number.

Code:

public static void FindTheDouble() {

    double LookFor = 2.29195;
                            //also tried adding a ".xxx" here
    for (double i = 1; i <= 5; i++) { //notice i is of type double
        System.out.println(i);
        if (i == LookFor) {
            System.out.println();
            System.out.println("Found the double: "+LookFor);
            break;          
        }   
    }
}

Output:

1.0
2.0
3.0
4.0
5.0

EDIT: Sorry, forgot to say what I was looking for. I was looking for it to go through ".xxxxxxx", but just got that output.

And is that a proper way of using a break statement? Any help is appreciated, thanks in advance!

Upvotes: 2

Views: 9422

Answers (6)

Taslim Oseni
Taslim Oseni

Reputation: 6273

Now, examine the code snippets below:

action:
//loop 1
for(int i = 0; i < 10; i++){
    //loop 2
    for(int j = 0; j < 10; j++){
        if(i == (j - 2)){
            break action;
               }
      }
   }

In the code above, if the condition in the inner for-loop is met, the first loop breaks because the label declaration (action:) is right before the first loop.

Now, look at this:

//loop 1
for(int i = 0; i < 10; i++){
    //loop 2
    action:
    for(int j = 0; j < 10; j++){
        if(i == (j - 2)){
            break action;
               }
      }
   }

Obviously, in this case, it's the second loop that'd be broken if the conditions are met.

Finally, there is no fixed keyword for labels, you can use any name you like (thunder, fire, superman, anything) and you can also declare multiple identifiers in your code. I hope this helps.. Merry coding!

Upvotes: 0

Yahya
Yahya

Reputation: 14082

If you do not mind using DoubleStreamfrom Java 8, you can try something like this, but please consider these points:

  • Max. Digits After The Decimal Point Is 7 Digits (I haven't tested it for more)
  • The More Precision You Want, The More Time It Takes.
  • If The Precision Provided (i.e Step) Is Less Than The Target Double That You're Searching For -> It Will Not Find It (Normal Logic).

    import java.text.DecimalFormat;
    import java.util.stream.DoubleStream;
    
    public class DoubleSearch {
    
    public static void main(String[] args){
        //Testing
        System.out.println(search(0.0000001, 5, 0.1)); // true
        System.out.println(search(0.0000001, 4, 0.01)); // true
        System.out.println(search(0.0000001, 3, 0.001)); //true
        System.out.println(search(0.0000001, 0.5, 0.0001)); //true
        System.out.println(search(0.0000001, 1.1, 0.00001)); //true
        System.out.println(search(0.0000001, 5.25, 0.0000001)); //true
        System.out.println(search(0.0000001, 2, 1.0001));
        System.out.println(search(0.1, 5, 4.0001)); // false because no enough precision provided (0.1)
        System.out.println(search(0.1, 2, 3)); // false as it's out of range
        System.out.println(search(0.00001, 5, 2.29195)); // your example returns true (i.e found)
    }
    
    public static boolean search(double step, double max, double target){
        return DoubleStream.iterate(0, d-> d+step).limit((long)(max/step)).anyMatch(p-> 
                        Double.compare(Double.valueOf(new DecimalFormat("#.#######").format(p)),
                        Double.valueOf(new DecimalFormat("#.#######").format(target)))==0); 
    }
    
    }
    

Output:

true
true
true
true
true
true
true
false
false
true

Upvotes: 0

Taslim Oseni
Taslim Oseni

Reputation: 6273

About the final part of your question, a break statement terminates the nearest loop. For example, examine the code snippet below:

for(int i = 0; i < whatever; i++){
    for(int j = 4; j > 0; j--){
        if(i == j){
            break;
            }
         } //End of second for-loop
     } //End of first for-loop

The break statement in the code above terminates the second for-loop only. You can select which particular loop a break statement would break by using labels. Assuming I actually wanted the break statement to terminate the first loop, I'd just attach a label to it as shown:

here:
for(int i = 0; i < whatever; i++){
    for(int j = 4; j > 0; j--){
        if(i == j){
            break here;
            }
         } //End of second for-loop
     } //End of first for-loop

Note: You can use any word you want as the label; you can replace 'here' with any word except of course, keywords.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234745

Rest assured that i is a double, but i will never be 2.29195.

Using a double in a for loop requires careful consideration since repeated addition of a constant to a floating point can cause accumulating total to "go off" due to inexact conversions from decimal to binary. (Try it with i += 0.1 as the incrementation and see for yourself). But for small whole numbers you'd be absolutely fine although then the use of a double is, of course, pointless.

If you want to effectively count up by units of 0.00001 then use something like

for (int i = 100000; i <= 500000; ++i){
    double f = i * 0.00001;
}

Then f is as close to the number that you really want as an IEEE754 double allows.

Upvotes: 1

Raphael
Raphael

Reputation: 1800

You want to walk your double number each 0.000001 until you find 2.29195, simply add 0.000001 to i at each interaction:

double LookFor = 2.29195;

    for (double i = 1; i <= 5; i += 0.00001) {
        System.out.println(i);
        if (i == LookFor) {
            System.out.println();
            System.out.println("Found the double: "+LookFor);
            break;          
        }   
    }
}

Not knowing exactly what you are trying to achieve, instead of using break you cloud use a while clause:

double LookFor = 2.29195;
double i = 1;
while(i != LookFor && i <= 5){
    System.out.println(i);
    i += 0.00001;
}
System.out.println("Found the double: "+LookFor);

Last, consider user BigDecimal instead of double to prevent drifting float issues.

Upvotes: 0

mba12
mba12

Reputation: 2792

You could do something like this:

public static void FindTheDouble() {

double LookFor = 2.29195;

for (double i = 1.0; i <= 5.0; i+=0.00005) {
    System.out.println(i);
       if (i == LookFor) {
           System.out.println();
           System.out.println("Found the double: "+LookFor);
           break;          
       }   
   }
}

Your break statement is correct.

Your equality statement might fail with doubles. Instead you want to do something like this:

if (Math.abs((i - LookFor)) < 0.0000001)

The double can have extraneous values at extended decimal places that can interfere with the success of your equality comparison. Instead it is better to check that the two double values are within some degree of precision that is acceptable to you.

Upvotes: 0

Related Questions