GY-63_MS5611/libraries/randomHelpers/randomHelpers.h

85 lines
1.7 KiB
C
Raw Normal View History

2021-01-29 06:31:58 -05:00
#pragma once
//
// FILE: randomHelpers.h
2022-04-15 14:51:51 -04:00
// AUTHOR: Rob Tillaart
// VERSION: 0.2.4
2021-01-29 06:31:58 -05:00
// PURPOSE: Arduino library with helper function for faster random bits
// URL: https://github.com/RobTillaart/randomHelpers
#include "Arduino.h"
2022-04-15 14:51:51 -04:00
#define RANDOM_HELPERS_VERSION (F("0.2.4"))
2021-12-27 14:38:20 -05:00
2021-01-29 06:31:58 -05:00
// the idea is to have one buffer ( __randomBuffer) which holds 32 random bits.
// Every call fetches bits from that buffer and if it does not hold enough
2021-11-15 11:10:01 -05:00
// bits any more it fills the buffer first. This way the relative expensive
2021-01-29 06:31:58 -05:00
// calls to random() which produces a 32 bit number are minimized in an
2021-11-15 11:10:01 -05:00
// efficient way.
2021-01-29 06:31:58 -05:00
//
// TBD: put it in a class ?
///////////////////////////////////////////////////////////////////////////
//
// An example of a simple pseudo-random number generator is the
// Multiply-with-carry method invented by George Marsaglia.
// it has two initializers (not zero) which can be changed
// to seed the generator.
//
2022-04-15 14:51:51 -04:00
uint32_t Marsaglia();
2021-11-15 11:10:01 -05:00
2022-04-15 14:51:51 -04:00
bool seedMarsaglia(uint32_t a, uint32_t b);
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint32_t getRandom32();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
bool getRandom1();
2021-01-29 06:31:58 -05:00
// typical use
2022-04-15 14:51:51 -04:00
bool inline flipCoin();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint8_t getRandom4();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint8_t getRandom5();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint8_t getRandom6();
2021-01-29 06:31:58 -05:00
// typical use
2022-04-15 14:51:51 -04:00
uint8_t throwDice();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint8_t getRandom8();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint16_t getRandom16();
2021-01-29 06:31:58 -05:00
2022-04-15 14:51:51 -04:00
uint32_t getRandom24();
2021-11-15 11:10:01 -05:00
2022-04-15 14:51:51 -04:00
uint64_t getRandom64();
2021-01-29 06:31:58 -05:00
/*
// works well for 1..16; but above it is worse
uint32_t getRandomBits(uint8_t n)
{
if (__randomIdx < n)
{
__randomBuffer = getRandom32();
__randomIdx = 32;
}
uint32_t rv = __randomBuffer & ((1UL << n) - 1);
__randomBuffer >>= n;
__randomIdx -= n;
return rv;
}
*/
// n = 1..31
// TODO: performance gain too low for n > 16
2022-04-15 14:51:51 -04:00
uint32_t getRandomBits(uint8_t n);
2021-01-29 06:31:58 -05:00
2021-11-15 11:10:01 -05:00
2021-01-29 06:31:58 -05:00
// -- END OF FILE --
2021-11-15 11:10:01 -05:00