Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
Random number range, exclude 0

I have the following function that generates a random number between -10 and 2:

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

static int
getRandomReturnCode(void)
{
    int N = 2,
        M = -10;

    srand(time(NULL));

    r = M + rand() / (RAND_MAX / (N - M + 1) + 1);

    if (r == 0){
        getRandomReturnCode();
    }

    return r;
}

Currently, if a return code of 0 (success) is returned, it will recursively call the function over until a non-zero return code is met and returned. What can I do to improve my code such that 0 is excluded from the range of randomly chosen numbers?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Whatever you do, don't redraw if a returned value is 0: that will introduce statistical bias into the result.

The best thing to do here is to draw between -10 and 1 inclusive and add 1 to any non-negative output.

Finally, call srand once else you'll ruin the generator's statistical properties.

(Briefly - since this comment is more for the mathematics site - and restricting the argument to a linear congruential generator, what tends to happen if you omit generated values is that you increase the variance of the resulting distribution so it's no longer uniform. A previously drawn small number will be linearly related to the subsequent drawing as the generator's modulus will have no effect. This autocorrelation - necessary for the resulting distribution to be uniform - of adjacent drawings will be curtailed if drawings are discarded and that increases the sample variance.)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda