![]() |
Forum Index : Microcontroller and PC projects : Trouble in RND land
Author | Message | ||||
fiziwig Newbie ![]() Joined: 09/07/2020 Location: United StatesPosts: 22 |
Here's a simple program that exposes a serious bug: Option Default Integer dim c(9) for i=0 to 9 c(i)=0 next i for i = 1 to 100000 k = int(rnd*9+0.5) c(k)=c(k)+1 next i for i=0 to 9 f! = c(i) / 100000.0 print i;f! next i There are ten possible integer outcomes, 0..9, so after running 100,000 times there should be roughly 10% in each array slot from c(0) to c(9). However, that's not what happens. Here is one sample run: 0 0.05602 1 0.10991 2 0.11019 3 0.10858 4 0.11078 5 0.11156 6 0.11264 7 0.11179 8 0.11175 9 0.05678 The distribution is wrong, with c(0) and c(9) getting only 5% and the others getting around 11%. I get the same result if I remove the "Option Default Integer" The distribution kinda looks like it has "tails" like a normal distribution. At any rate, there is a definite bias away from the two tails. You can get a decent flat distrubtion with a hack like this, using some semi-large prime as a multiplier and your desired range as the modulus: int(rnd*11213+0.5) mod 10 After 100,000 iterations this gives 10% to 4 decimal places. |
||||
flip Senior Member ![]() Joined: 18/07/2016 Location: AustraliaPosts: 114 |
Hi fiziwig, There's no bug there. The rnd*9+0.5 will give a random distribution between 0.5 and 9.5 (which the integer function changes to 0-9 but with incorrect weighting Try k = int(rnd*10) Regards Phil Edited 2020-08-06 13:27 by flip |
||||
TassyJim![]() Guru ![]() Joined: 07/08/2011 Location: AustraliaPosts: 6283 |
It was covered in depth not long ago. https://www.thebackshed.com/forum/ViewTopic.php?TID=12284&PID=149205#149205#149199 Jim VK7JH MMedit |
||||
![]() |
![]() |
The Back Shed's forum code is written, and hosted, in Australia. | © JAQ Software 2025 |