0

I was trying to generate some points at 0.1 intervals along a unit[-1, +1] horizontal line. Here is the code.

for (float x = -1; x < 1.1f; x += 0.1f)
{
    line.points.push_back(Point(x, 0.5f, x * 1.0f));
}

When I tried to draw the points later,

for (size_t i = 1; i < tLine.points.size(); i++) 
{
    std::cout << "drawing" << '\n';
    DrawLine(
        (int32_t)tLine.points[i].x,
        (int32_t)tLine.points[i].y,
        (int32_t)tLine.points[i - 1].x,
        (int32_t)tLine.points[i - 1].y,
        olc::BLACK);
}

I noticed that "drawing" printed on the console stops after 11 iterations the program freezes. After some debugging, I found out that the problem is the first for loop to generate the points. When I printed out the x value of that for loop, it gave me

-1
-0.9
-0.8
-0.7
-0.6
-0.5
-0.4
-0.3
-0.2
-0.0999999
7.45058e-08 // ???
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1

As you can see the value that is supposed to be 0 is some nonsense value. The one before that is off by a little as well.

In that for loop, 0.1 is being added to -0.0999999 to give 7.45058e-08. I also manually tried to add the same two numbers but it gives 1.04308e-07 (I was hoping for it to give 0). What is going on and how can I solve this problem? Thanks.

  • 3
    don't iterate a floating point number, use integer – paladin Jun 07 '21 at 11:46
  • 1
    don't use `float`s for the loop counter. Instead do `float x0 = -1; float delta = 0.1;` and `for (int i=0;i< num_points; ++i) { x = x0 + i*delta; }` – 463035818_is_not_an_ai Jun 07 '21 at 11:46
  • 2
    btw `7.45058e-08` is not non-sense. It is as close to `0` as you can expect from adding `float`s – 463035818_is_not_an_ai Jun 07 '21 at 11:47
  • What's going on is this is how floating point numbers work in all modern programming languages. The linked question gives a fuller explanation of the reason you're seeing this. Once you understand what's happening, on the fundamental level, you should be able to figure out the appropriate solution/workaround for your situation. But you need to understand the fundamental principles of floating point values, first. – Sam Varshavchik Jun 07 '21 at 11:47

0 Answers0