You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WMath.cpp 1.7KB

7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Part of the Wiring project - http://wiring.org.co
  3. Copyright (c) 2004-06 Hernando Barragan
  4. Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/
  5. This library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. This library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General
  14. Public License along with this library; if not, write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. */
  18. #include <stdint.h>
  19. static uint32_t seed;
  20. void randomSeed(uint32_t newseed)
  21. {
  22. if (newseed > 0) seed = newseed;
  23. }
  24. void srandom(unsigned int newseed)
  25. {
  26. seed = newseed;
  27. }
  28. int32_t random(void)
  29. {
  30. int32_t hi, lo, x;
  31. // the algorithm used in avr-libc 1.6.4
  32. x = seed;
  33. if (x == 0) x = 123459876;
  34. hi = x / 127773;
  35. lo = x % 127773;
  36. x = 16807 * lo - 2836 * hi;
  37. if (x < 0) x += 0x7FFFFFFF;
  38. seed = x;
  39. return x;
  40. }
  41. uint32_t random(uint32_t howbig)
  42. {
  43. if (howbig == 0) return 0;
  44. return random() % howbig;
  45. }
  46. int32_t random(int32_t howsmall, int32_t howbig)
  47. {
  48. if (howsmall >= howbig) return howsmall;
  49. int32_t diff = howbig - howsmall;
  50. return random(diff) + howsmall;
  51. }
  52. unsigned int makeWord(unsigned int w) { return w; }
  53. unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }