Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 16:56 02 Aug 2025 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : Trouble in RND land

Author Message
fiziwig
Newbie

Joined: 09/07/2020
Location: United States
Posts: 22
Posted: 02:52am 06 Aug 2020
Copy link to clipboard 
Print this post

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: Australia
Posts: 114
Posted: 03:26am 06 Aug 2020
Copy link to clipboard 
Print this post

Hi fiziwig,
There's no bug there.
  Quote  k = int(rnd*9+0.5)

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: Australia
Posts: 6283
Posted: 03:36am 06 Aug 2020
Copy link to clipboard 
Print this post

It was covered in depth not long ago.
https://www.thebackshed.com/forum/ViewTopic.php?TID=12284&PID=149205#149205#149199

Jim
VK7JH
MMedit
 
Print this page


To reply to this topic, you need to log in.

The Back Shed's forum code is written, and hosted, in Australia.
© JAQ Software 2025