Skip to content

Updated rand() implementation seems incorrect #259

@raygard

Description

@raygard

I see in FIXES: "Fix incorrect divisor in rand() - it was returning even random numbers only."

I don't understand about even random numbers from awk rand(); rand() returns "a floating point pseudo-random number n, such that 0<=n<1." (posix). How can a fraction be even or odd?

The fix changed (Awkfloat) random() / (0x7fffffffL + 0x1UL) to (Awkfloat) random() / RAND_MAX. There are a couple problems here.

random() returns a max value of 2**31-1; if you divide (Awkfloat)random() by RAND_MAX (equals 2**31-1 in my gcc), the result can range up to (and including) 1, but awk rand() is supposed to be less than 1. Which is why the original code divided by (0x7fffffffL + 0x1UL), i.e. 2**31.

RAND_MAX happens to be 2**31-1 on some C implementations, but ISO C and POSIX say RAND_MAX is "Maximum value returned by rand(); at least 32767." So RAND_MAX has nothing to do with random() and need not be 2**31-1.

What was the actual problem that prompted the change?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions