I have the following code:
#include <iostream>
#include <math.h>
#include <vector>
int main() {
size_t N = 20;
double from = 0.0;
double to = 1.0;
std::vector<double> xVec{};
double h = (to - from) / double(N);
for (double x = from; x <= to; x += h) { // not entering x == 1.0
xVec.push_back(x);
std::cout << x << "\n";
}
std::cout << "\n";
double x = 0.9;
const std::vector<double>::iterator it = std::lower_bound(xVec.begin(), xVec.end(), x);
std::cout << x << " " << *it << " " << (x == *it) << "\n"; // states that 0.9 != 0.9
}
Which gives this really strange output:
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
0.9 0.9 0
I have 2 questions about this:
- Why is my loop not entering
x == 1.0, when I am using<=in the loop criterion? - How is it possible that a double given by
std::lower_boundis not equal to another double with the same value?