tags:

views:

79

answers:

3

How to Generate the random number from 0.5 to 1.0 .

+6  A: 

You can try:

float RandomBetween(float smallNumber, float bigNumber)
{
    float diff = bigNumber - smallNumber;
    return (((float) rand() / RAND_MAX) * diff) + smallNumber;
}
Adrian Faciu
+2  A: 

You should be able to use something like:

double x = ((double)rand()) / ((double)RAND_MAX) / 2.0 + 0.5;

The division by RAND_MAX gives you a value from 0 to 1, dividing that by two drops the range to 0 to 0.5, then adding 0.5 gives you 0.5 to 1. (inclusive at the low end and exclusive at the top end).

paxdiablo
A: 

Some thing like bellow will help you.

double random(double start, double end)
{
    double moduleValue = ((end - start) *10); //1.0 - .5 --> .5 -->> 5
    double randum = rand() % moduleValue; // restrict the random to your range
    //if rendum == 2 --> .2 + .5 --> .7 in the range .5 -- 1.0

    return (randum / 10) + start; // make your number to be in your range
}

Test code for clarification

#include <stdio.h>
#define RAND_NUMBER 14
#define INT_FLAG 10
int main (int argc, const char * argv[]) {
    // insert code here...
    double start = .5;
    double end = 1.0;

    double moduleValue = ((end - start) * INT_FLAG);

    int randum = (RAND_NUMBER / moduleValue);

    double result = ((double)randum/INT_FLAG) + start;
    printf("%f",result);
    printf("Hello, World!\n");
    return 0;
}
Girish Kolari
Isn't that artificially restricting it to steps of 0.1? Why would you do that rather than use the full double range?
paxdiablo
check the clarification code --- when you try to divide the .5 it act as 1/2 in mathematics because of which the number generated will not be in you range
Girish Kolari