Floating rand in C matrix

Asked

Viewed 276 times

1

Good afternoon, I am using the Rand function to generate random numbers in a C matrix, but I can only generate integers. I would like to generate floating numbers. I did not find anything of the type in the documentation (although seen Rand is used for integers). It is possible?

  • this answer would help you? https://answall.com/a/128469/110782

  • Possible duplicate of Rand between numbers with comma

  • @Vinicius, helped a lot, thanks!

  • 1

    @Luiz, it worked, thanks anyway!

1 answer

0

The function rand() of the standard library stdlib.h generates only pseudo-random numbers whole amid 0 and RAND_MAX.

A generic solution would be to implement a function capable of generating floating point values between 0 and 1, look at you:

double randf( void )
{
    return rand() / ((double)RAND_MAX);
}

Another valid solution would be to use a function capable of generating random numbers between 0 and a predetermined maximum value:

double randf( double max )
{
    return rand() / ( RAND_MAX / max );
}

And finally, a function capable of generating floating point numbers within a pre-established range:

double randf( double min, double max )
{
    return min + ( rand() / ( RAND_MAX / ( max - min ) ) );
}

Testing:

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


double randf( double min, double max )
{
    return min + ( rand() / ( RAND_MAX / ( max - min ) ) );
}

int main()
{
    int i = 0;

    /* Inicializa gerador de numeros aleatorios usando o horario
     * do sistema como semente */
    srand(time(NULL));

    /* Gera e exibe 10 numeros aleatorios entre 1.5 e 1.9 */
    for( i = 0; i < 10; i++ )
        printf( "%g\n", randf( 1.5, 1.9 ) );

    return 0;
}

Possible Exit:

1.52526
1.777
1.77164
1.83923
1.58224
1.60071
1.88104
1.64621
1.78467
1.77367

Browser other questions tagged

You are not signed in. Login or sign up in order to post.