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.