Skip to content

Commit

Permalink
Implement rand/srand as 16-bit xorshift
Browse files Browse the repository at this point in the history
This is a fairly high quality rand; it has a low period (lower than that
required by POSIX), but few other defects given its performance.
  • Loading branch information
mysterymath committed Jan 14, 2024
1 parent eaf7bd5 commit 08494f6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
16 changes: 16 additions & 0 deletions mos-platform/common/c/stdlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -479,3 +479,19 @@ strtoui(const char *__restrict__ nptr, char **__restrict__ endptr, int base) {

return (sign == '+' || is_error) ? rc : -rc;
}

// A 16-bit xorshift generator with constants well suited to 8-bit systems.
// Values found by George Marsaglia for the Z80:
// http://www.retroprogramming.com/2017/07/xorshift-pseudorandom-numbers-in-z80.html

static unsigned seed = 1;

__attribute__((weak)) int rand(void) {
unsigned x = seed;
x ^= x << 7;
x ^= x >> 9;
x ^= x << 8;
return seed = x;
}

__attribute__((weak)) void srand(unsigned s) { seed = s; }
3 changes: 3 additions & 0 deletions mos-platform/common/include/stdlib.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ int strtoi(const char *__restrict__ nptr, char **__restrict endptr, int base);
unsigned int strtoui(const char *__restrict__ nptr, char **__restrict endptr,
int base);

int rand(void);
void srand(unsigned seed);

// clang-format off
/**
Simple malloc/free implementation.
Expand Down

0 comments on commit 08494f6

Please sign in to comment.