math - Equal probability in Java -


how can math.random() call have absolute equal probability 4 cases? (ie 0.25 case 1, 0.25 case 2, 0.25 case 3, 0.25 case 4)?

i 0.05 case 1, 0.075 case 2, 0.45 case 3 , 0.425 case 4.

been trying work out why hours not success.

int direction = 0;          // select random number          randno = (int) math.round(math.random() * 3);          // convert direction          while (direction == 0) {             if (randno == 0 && !iswall(robot, robot.left)) direction = robot.left;             else if (randno == 1 && !iswall(robot, robot.right)) direction = robot.right;             else if (randno == 2 && !iswall(robot, robot.behind)) direction = robot.behind;             else if (!iswall(robot, robot.ahead)) direction = robot.ahead;             else randno = (int) math.round(math.random() * 3);         } 

math.random() * 3 results in values in range [0, 3). appplying math.round means:

  • [0, 0.5) becomes 0. - 0.5 out of 3 means 1/6th probability.
  • [0.5, 1.5) becomes 1 - twice big above range, 2/6th
  • [1.5, 2.5) becomes 2 - same above, 2/6th
  • [2.5, 3) becomes 3. 1/6th again.

next up, combine unevenly distributed numbers iswall. cases (randno == 0 && iswall(robot, robot.left)) (value 0 there wall) added last case.

what need a) method

double probability = math.random(); if (probability < 0.25) {     .. 

that doesn't have screwed distribution.

b) don't let choices fall through. last case in code needs limit randno or eats cases don't belong there.

also may have rethink you're measureing. count when decides go left there wall? choices can walls don't care. perfect distribution possible when there no walls.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -