{"id":1159,"date":"2010-07-01T20:51:42","date_gmt":"2010-07-02T03:51:42","guid":{"rendered":"https:\/\/www.reenigne.org\/blog\/?p=1159"},"modified":"2010-07-01T20:51:42","modified_gmt":"2010-07-02T03:51:42","slug":"random-number-generation-on-8-bit-avr","status":"publish","type":"post","link":"https:\/\/www.reenigne.org\/blog\/random-number-generation-on-8-bit-avr\/","title":{"rendered":"Random number generation on 8-bit AVR"},"content":{"rendered":"<p>For my <a href=\"https:\/\/www.reenigne.org\/blog\/physical-tone-matrix\">physical tone matrix<\/a> I wanted a mode where at the start (or end) of each cycle the machine would pick a random \"on\" light and turn it off, and a random \"off\" light and turn it on. With 5-10 lights on, this makes a fairly nice little bit of random music - continually changing so it doesn't get too repetitive.<\/p>\n<p>To implement this I decided the best way was to pick a frame (the second one of the cycle turned out to be the most convenient) and decrement one of two variables \"randomOn\" or \"randomOff\" depending on whether the current LED within the frame was on or off. If the variable reached zero the LED would be toggled. That doesn't take too many cycles. But the sample before this frame we need to generate random numbers and initialize randomOn and randomOff with them. randomOn needs to be in the range 0..lightsLit-1 (where lightsLit is the number of \"on\" LEDs) and randomOff needs to be in the range 0..(255-lightsLit). So we need to generate two random numbers in the range 0..n-1 where n is in the range 1..255 as quickly as possible. I wanted to try to generate these numbers in a single sample as trying to spread the work across multiple samples makes the program much more complicated. That left me with about 300 cycles to generate two random numbers.<\/p>\n<p>The usual way of generating a random number in the range 0..n-1 is to generate a random number in a much larger range (say 0..65535) and use the modulo operation (\"remainder after division by n\") to get it into the range 0..n-1.<\/p>\n<p>Generating a 16-bit random number is done in a fairly standard way using a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Linear_congruential_generator\">Linear Congruential Generator<\/a> (I used the X = 214013*X + 2531011 variant because it cuts out a few multiplications). That by itself takes nine 8-bit by 8-bit multiplications and 56 cycles. I rewrote it myself in assembly language rather than using the built-in generator from avr-libc, because the latter it not very optimized (it uses a full 32-bit multiplication which is not necessary).<\/p>\n<p>If you use the 16-bit modulo function from libgcc it takes something like 215 cycles, which was too many. Even unrolled it's something like 144, which is still too many. I was about to embark on the work to spread this loop across several samples when I read <a href=\"http:\/\/blog.sigfpe.com\/2010\/05\/optimising-pointer-subtraction-with-2.html\">this<\/a> which describes a way of turning a division by a constant into a multiplication by a constant. That's not very useful for arbitrary division, since computing the multiplier constant is more work than just doing the division. But we're not doing arbitrary division here - we know something about our divisor n - it is no larger than 255. So it becomes practical to precalculate a table of multipliers and look up an entry in this table at runtime.<\/p>\n<p>The next problem is that that method only works when the division is exact (has remainder zero) which is no good for this application since it's the remainder we're interested in. But the classic bit-twiddling reference book <a href=\"http:\/\/www.hackersdelight.org\/\">Hacker's Delight<\/a> describes a variation which does work (for some divisors the dividend needs to be added back after the multiplication, and for some the result needs to be shifted right by a number of bits depending on the divisor). So our mod algorithm looks like this:<\/p>\n<ol>\n<li>Look up multiplier in table indexed by divisor<\/li>\n<li>Multiply dividend by multiplier<\/li>\n<li>Look up helper routine in table indexed by divisor (there are 18 variations - 9 possible shifts and either \"add\" or \"don't add\", but not all of them are used) and jump to it.<\/li>\n<li>Multiply by the divisor and subtract the result from the original dividend - the result is the remainder.<\/li>\n<\/ol>\n<p>The resulting mod routine takes 40-53 cycles (depending on divisor) giving 96-109 cycles for the entire random number routine. With various other bits of overhead, the random routine takes 253 cycles on this \"init\" sample and up to 29 per sample on the first frame of the cycle.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>For my physical tone matrix I wanted a mode where at the start (or end) of each cycle the machine would pick a random \"on\" light and turn it off, and a random \"off\" light and turn it on. With 5-10 lights on, this makes a fairly nice little bit of random music - continually [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[39],"tags":[],"class_list":["post-1159","post","type-post","status-publish","format-standard","hentry","category-algorithms"],"_links":{"self":[{"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/posts\/1159","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/comments?post=1159"}],"version-history":[{"count":1,"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/posts\/1159\/revisions"}],"predecessor-version":[{"id":1160,"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/posts\/1159\/revisions\/1160"}],"wp:attachment":[{"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/media?parent=1159"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/categories?post=1159"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.reenigne.org\/blog\/wp-json\/wp\/v2\/tags?post=1159"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}