-2

I know its possible to generate integer random number using

(rand() % (difference_between_upper_and_lower_limit)) + lower_limit

I'm wondering if theres a way to generate a number between 0.1 and 0.01. I've tried double speed = (rand() % 10)/100; But it always just gives me 0.0000000; Thanks in Advance!`

crooose
  • 111
  • 4
  • 10
  • 3
    `/100` is integer division. `/100.0` is floating point division. – user3386109 Aug 31 '18 at 01:59
  • 1
    Have you looked at `drand48`? It won't be perfect (i.e., the manipulations you would have to perform upon its result) but it might be adequate for what you need. Have a look [here](https://stackoverflow.com/questions/33058848/generate-a-random-double-between-1-and-1) for some ideas. – Jeff Holt Aug 31 '18 at 02:00
  • 4
    There are an infinite amount of numbers between 0.1 and 0.01. Do you mean that you want to generate a random number from the ten numbers in this set (0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10)? If not what do you mean? – Stuart Aug 31 '18 at 02:08
  • Possible duplicate of [Integer division always zero](https://stackoverflow.com/questions/9455271/integer-division-always-zero) – phuclv Aug 31 '18 at 03:59

3 Answers3

2

I think, you missed the type-casting part ==> ((double)(rand() % 10))/100;

Try this code.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
  // If you don't set the seed-value, you'll always get the same random numbers returned in every execution of the code
  srand(time(0));

  double speed = ((double)(rand() % 10))/100;
  printf("%f\n", speed );

  speed = ((double)(rand() % 10))/100;
  printf("%f\n", speed );

  speed = ((double)(rand() % 10))/100;
  printf("%f\n", speed );

  speed = ((double)(rand() % 10))/100;
  printf("%f\n", speed );

  return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Prabhakar
  • 41
  • 6
2

You can create an uniform distribution on an arbitrary interval with

((double)rand()/RAND_MAX)*(i_end-i_start)+i_start

where i_start and i_end denote the start and end of the interval.

In your case try

((double)rand()/RAND_MAX)*0.09+0.01
Osiris
  • 2,783
  • 9
  • 17
  • 2
    Let us call this uniform-ish. OK for basic programs. – chux - Reinstate Monica Aug 31 '18 at 03:32
  • @chux Yes, it gives at maximum `RAND_MAX+1` different results, which is most likely less then doubles in that interval. There are probably better functions to use, like `drand48()`, but i wanted to stick with the random function he mentioned in his question. – Osiris Aug 31 '18 at 03:57
1
double upper_limit = .1;
double lower_limit = .01;
double value = ((upper_limit-lower_limit)*rand())/RAND_MAX + lower_limit;
selbie
  • 100,020
  • 15
  • 103
  • 173