views:

196

answers:

4

Hi,

I want to use the for loop for my problem, not while. Is it possible to do the following?:

for(double i = 0; i < 10.0; i+0.25)

I want to add double values.

+13  A: 

Use i += 0.25 instead

JamesMLV
+1 12 more to go..
org.life.java
+2  A: 

for(double i = 0; i < 10.0; i+=0.25) { //... }

The added = indicates a shortcut for i = i + 0.25;

Valchris
+18  A: 

To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop:

for (int n = 0; n <= 40; n++) {
    double i = 0.25 * n;
    // ...
}
rsp
+3  A: 

James's answer caught the most obvious error. But there is a subtler (and IMO more instructive) issue, in that floating point values should not be compared for (un)equality.

That loop is prone to problems, use just a integer value and compute the double value inside the loop; or, less elegant, give yourself some margin: for(double i = 0; i < 9.99; i+=0.25)

Edit: the original comparison happens to work ok, because 0.25=1/4 is a power of 2. In any other case, it might not be exactly representable as a floating point number. An example of the (potential) problem:

 for(double i = 0; i < 1.0; i += 0.1) 
     System.out.println(i); 

prints 11 values:

0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
leonbloy
The original question has `i < 10.0`. Can you explain again how the standard speech about floating-point equality applies here? (as a note, when your floating-point computations are exact it is perfectly safe to use equality).
Pascal Cuoq
'when your floating-point computations are exact' is a tricky sentence. Because you must be sure that your decimal numbers admit an exact representation in Java's floating number format (0.25 happens to admit it, 0.2 or 0.1 don't) I added an example.
leonbloy
@leonbloy I am trying to understand how adding 0.01 helps. If the computations are not exact, the floating-point result is as likely to be below the real result as above it, so your "fix" may cause one additional iteration in a loop that already has too many iterations compared to the programmer's intent.
Pascal Cuoq
@Pascal: you're right! I had corrected it, though. Anyway, that's bad practice also.
leonbloy