Shop OBEX P1 Docs P2 Docs Learn Events
Question to FLEXC:: rand() [solved] — Parallax Forums

Question to FLEXC:: rand() [solved]

ReinhardReinhard Posts: 489
edited 2020-07-14 11:55 in Propeller 2
Hi forumist's,
I'm an user of fastspin/FLEXC
Propeller Spin/PASM Compiler 'FastSpin' (c) 2011-2020 Total Spectrum Software Inc.
Version 4.2.3 Compiled on: Jun 29 2020
In stdlib.h I found
#define RAND_MAX 0x7fff
I make tests i.e.
int z = rand();
printf("%d \n",z);

I get values larger than 0x7FFF.
For a project I need a float random number. So I want to make a way similar this: (float) (rand() / RAND_MAX)
but therefore I need to know the max. Number delivered by rand().

Has anyone an idea ?

Comments

  • From looking at the source code for the rand function, RAND_MAX should be 0x7fffffff instead of 0x7fff.
  • The flex libraries actually have a built in _randfloat() function (used by BASIC for its rnd() function) which generates a random number between 0.0 and 1.0. Here's an example of its use:
    // print some random floating point numbers
    #include <stdio.h>
    
    extern float _randfloat(); // built in
    
    void main() {
        for(int i = 0; i < 20; i++) {
            printf("%f\n", _randfloat());
        }
    }
    
  • evanhevanh Posts: 15,916
    I've always thought floats were inappropriate store of random numbers due to exponent component having no meaning to randomness.
  • Thank you for all responses.
    The randfloat() function is exact what I need.
    In the meantime I do this workaround:
    int z = (rand() & 0x7FFF);
    

    best regards
    Reinhard
Sign In or Register to comment.