Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment double by smallest possible valueTest

Tags:

c++

double

I want to increment a double value from the smallest possible (negative) value it can take to the largest possible value it can take.

I've started off with this:

int main()
{
  double min(numeric_limits<double>::min());

  double i(min);

  while(i < 0);
  {
      cout << i << endl;
      i += min ;
  }
}

Unfortunately, this doesn't produce the desired result - the while loop is skipped after one iteration.

Is there a better way to accomplish my goal?

like image 677
nf313743 Avatar asked Oct 31 '25 01:10

nf313743


1 Answers

I'm guessing at what you want from your code: You want to start with largest possible negative value and increment it toward positive infinity in the smallest possible steps until the value is no longer negative.

I think the function you want is nextafter().

int main() {
    double value(-std::numeric_limits<double>::max());
    while(value < 0) {
        std::cout << value << '\n';
        value = std::nextafter(value,std::numeric_limits<double>::infinity());
    }
}
like image 107
bames53 Avatar answered Nov 01 '25 16:11

bames53



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!