Thread: More thoughts on random floats

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    277

    Question More thoughts on random floats

    I was reading this interesting thread about generating random ranges of floating point values.

    What about closed ranges? I was wondering if a simple binary partitioning approach could be used.

    Code:
    #include "stdbool.h"
    
    double random_within_range_with(bool (*extract_bit)(void*), void* data, double low, double high)
    {
     if(low > high)
      return random_within_range_with(extract_bit, data, high, low);
     double range = (high - low) / 2;
     double sum = range;
     for(;;)
     {
      range /= 2;
      if(extract_bit(data))
       sum += range;
      else
       sum -= range;
      if(range == 0)
       break;
     }
     return low + sum;
    }
    
    #include "stdlib.h"
    #include "time.h"
    
    bool extract_srand_bit(void* unused)
    {
     static bool init = true;
     if(init)
     {
      srand(time(NULL));
      init = false;
     }
     return rand() & 1;
    }
    
    double random_within_range(double low, double high)
    {
     return random_within_range_with(extract_srand_bit, NULL, low, high);
    }
    
    #include "stdio.h"
    
    int main(int argc, char** argv)
    {
     puts("Random [LOW] [HIGH]");
     double low = -1;
     if(argc > 1)
      low = atof(argv[1]);
     double high = 1;
     if(argc > 2)
      high = atof(argv[2]);
     printf("Low: %g\n", low);
     printf("High: %g\n", high);
     for(;;)
     {
      printf(" %g\n", random_within_range(low, high));
      getchar();
     }
    }
    I'm trying to avoid platform-specific particularities. Does that look like an acceptable approach?
    Last edited by Sir Galahad; 04-20-2021 at 03:27 PM. Reason: stdbool.h

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random array generator for floats
    By tomelk31 in forum C Programming
    Replies: 7
    Last Post: 02-19-2011, 07:53 AM
  2. More random thoughts on constructing scripting languages.
    By suzakugaiden in forum Tech Board
    Replies: 2
    Last Post: 01-21-2006, 01:30 AM
  3. UML and C++: Your Thoughts
    By Mister C in forum C++ Programming
    Replies: 5
    Last Post: 03-16-2003, 12:56 PM
  4. more thoughts....
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 05-07-2002, 02:34 AM
  5. thoughts
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 27
    Last Post: 04-29-2002, 10:00 PM

Tags for this Thread