1

I am using Code::Block 16.01, the current version, that come with compiler. The problem is when I change xMax to 1.2, the result does not change. It produce the same result as xMax=1.1. Did I do something wrong with my C code? Or is this a compiler problem? Here is my MWE:

#include<stdio.h>
int main()
{
    double xMin=1.0;
    double xMax=1.1;
    double x=xMin;
    double h=0.1;
    while(x <= xMax)
    {
        printf("x=%f\n",x);
        x=x+h;
    }
    return 0;
}
Say OL
  • 234
  • 1
  • 3
  • 10
  • And "*the same result*" is? – alk Jun 19 '16 at 08:17
  • 2
    "Is it a compiler bug" no it isn't. – n. m. could be an AI Jun 19 '16 at 08:18
  • 1
    These constants cannot be exactly represented as floating point numbers. The `%f` format doesn't display very much precision, but if you look more closely, you will see that `0.1` is actually slightly larger than the intended number. – Tom Karzes Jun 19 '16 at 08:24
  • @alk: the result of my code is **1.000000**, **1.100000**. And if we let **xMax=1.2**, then the result is the same as the case **xMax=1.1**. – Say OL Jun 19 '16 at 10:28

1 Answers1

1

You have a float point precision problem. Since 1.2 cannot be represented exactly in the binary form, there is a precision loss. Your code should work if you change 1.2 to something bigger, let's say, 1.201

In general, please try to avoid = in float point comparisons.

GMichael
  • 2,726
  • 1
  • 20
  • 30
  • It depends. It was greater with my compiler. I tried it here: http://ideone.com/ – GMichael Jun 19 '16 at 08:27
  • No. I say that in both cases it printed only two lines: `x=1.000000` and `x=1.100000` – GMichael Jun 19 '16 at 08:29
  • Sorry, my original comment was backwards. Here's what I meant to say: `1.0`, plus `0.1`, plus `0.1` is *greater than* `1.2`, so the last intended iteration is skipped. Actually this is consistent with what you posted. I think I misread it originally. – Tom Karzes Jun 19 '16 at 08:33
  • Yes. But it does not matter is it less or greater. The problem is the same - `precision` – GMichael Jun 19 '16 at 08:35
  • Well, it affects the observed behavior. If it had been the other way around, the problem would not have been noticed. – Tom Karzes Jun 19 '16 at 08:35
  • Correct. I know some financial applications where there is no floating point numbers at all. All calculations are performed with integers and the results represented as `dddd.dddd` – GMichael Jun 19 '16 at 08:46
  • Yes, fixed point representations avoid the problem. It's not just an issue of precision. Any base 2 floating point representation would have the same problem, regardless of how many bits of precision the mantissa can hold. – Tom Karzes Jun 19 '16 at 08:48