Thread: How to generate a random number in the interval of -1 and 1?

  1. #16
    Registered User
    Join Date
    Sep 2020
    Posts
    425
    Quote Originally Posted by flp1969 View Post
    That's interesting, Malcom! I completely forgot about linear interpolation!

    Code:
    #include <stdlib.h>
    #include <float.h>
    
    #define lerp(min_, max_, norm) \
      ( (min_)*(1.0 - (norm)) + (max_)*(norm) )
    
    double symmetrical_rand ( void )
    {
      double d;
    
      d = ( double ) rand() / RAND_MAX;
      return lerp ( -1.0 + DBL_EPSILON, 1.0 - DBL_EPSILON, d );
    }
    There is one more number between 1.0-DBL_EPSILON and 1.0:

    Code:
    #include <float.h>
    #include <stdio.h>
    
    
    void printhex(void *x, size_t s) {
      for(size_t i = 0; i < s; i++)
        printf("%02X ",((unsigned char *)x)[i]);
      putchar('\n');
    }
    
    
    int main(int argc, char *argv[]) {
       double a = 1.0;
       double b = 1.0-DBL_EPSILON/2;
       double c = 1.0-DBL_EPSILON;
       printf("%e\n", DBL_EPSILON);
       printf("%32.30e\n", a);
       printf("%32.30e\n", b);
       printf("%32.30e\n", c);
       printhex(&a, sizeof(a));
       printhex(&b, sizeof(b));
       printhex(&c, sizeof(c));
    
    
    }
    Gives the following output:
    Code:
    2.220446e-16
    1.000000000000000000000000000000e+00
    9.999999999999998889776975374843e-01
    9.999999999999997779553950749687e-01
    00 00 00 00 00 00 F0 3F
    FF FF FF FF FF FF EF 3F
    FE FF FF FF FF FF EF 3F

  2. #17
    Registered User
    Join Date
    Oct 2019
    Posts
    43
    Guys, I am sorry to be late to deliver THANKS to everyone. Appreciated so much that I have learned from your code. Thanks again.

  3. #18
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Quote Originally Posted by hamster_nz View Post
    There is one more number between 1.0-DBL_EPSILON and 1.0
    Ahhh... of course, since we change the scale from 2⁰ to 2⁻¹! Nice catch.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 10-01-2016, 12:54 AM
  2. random number from interval [0,1]
    By nerio in forum C Programming
    Replies: 11
    Last Post: 02-07-2013, 07:24 AM
  3. Replies: 3
    Last Post: 07-24-2012, 09:30 AM
  4. Generate Random Number
    By peacealida in forum C++ Programming
    Replies: 10
    Last Post: 04-06-2008, 08:57 AM
  5. generate a random number
    By waxydock in forum C++ Programming
    Replies: 5
    Last Post: 06-05-2005, 07:43 PM

Tags for this Thread