-3

I need to randomly generate numbers (using random()) from -1 to 1 that are doubles. For example the output would be something like:

1, -0.3324, 0.7821, 0.9823, -0.111

etc... this is what I was trying to do walk_Length = (double)rand()%2 - 1;

Brian
  • 5
  • 2
  • I saw that tutorial, but I was wondering how can I modify that to get it to be from -1 to 1 inclusive? – Brian Mar 30 '18 at 00:04
  • It's not a "tutorial" and you should read it in full because it tells you how to give a range, with multiple approaches. – Lightness Races in Orbit Mar 30 '18 at 00:06
  • Doubles are not precise values ​​so some of the values ​​do not exist, for example 0.88 do not exist in doubles and floating. see https://stackoverflow.com/questions/9999221/double-precision-decimal-places – eyllanesc Mar 30 '18 at 00:07

1 Answers1

0

You might get away with something like

double walk_Length = static_cast<double>(rand()) / RAND_MAX * 2 - 1;
Sid S
  • 5,887
  • 2
  • 12
  • 23