nf313743
nf313743

Reputation: 4227

Increment double by smallest possible valueTest

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?

Upvotes: 4

Views: 1745

Answers (3)

Erik Jan
Erik Jan

Reputation: 1

The following runs through all float-values 'in order'. The steps between successive values become smaller as u.mind increases. No guarantee this is correct and it will take a long time to complete and this isn't portable and it will take even longer for doubles and... etc. etc.

#include <cassert>
#include <iostream>
#include <limits>

union umin {
   float mind;
   int mini;
} u;

int main()
{
   u.mind = std::numeric_limits<float>::max();
   std::cout << -u.mind << " " << u.mini << std::endl;
   while ( u.mind > 0 ) {
      float previous = u.mind;
      u.mini -= 1;
      std::cout << -u.mind << " " << u.mini << " " << previous - u.mind << std::endl;
      assert( previous > u.mind );
   }
}

Upvotes: 0

bames53
bames53

Reputation: 88155

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());
    }
}

Upvotes: 5

kennytm
kennytm

Reputation: 523214

Firstly,

  while(i < 0);           // <--- remove this semicolon
  {
      cout << i << endl;
      i += min ;
  }

Then, std::numeric_limits<double>::min() is a positive value, so i < 0 will never be true. If you need the most negative value, you'll need

double min = -std::numeric_limits<double>::max();

but I don't know what your i += min line is supposed to do. Adding two most negative number will just yield −∞, and the loop will never finish. If you want to add a number, you'll need another variable, like

double most_negative = -std::numeric_limits<double>::max();
double most_positive = std::numeric_limits<double>::max();

double i = most_negative;
while (i < 0)
{
   std::cout << i << std::endl;
   i += most_positive;
}

Of course this will just print the most negative number (-1.8e+308), and then i becomes 0 and the loop will exit.

Upvotes: 0

Related Questions