Sandbox · Experiment

Dice Roll Histogram

This sandbox program demonstrates how random dice rolls statistically distribute. The results are displayed as a histogram, making frequencies and relative parts directly visible.

Format Pygame
Theme Chance & Statistics
Display Histogram
Interaction Keyboard & Mouse
Dice Roll Histogram

Introduction

This sandbox program uses pygame to visually display the frequency of dice rolls.

The program simulates dice rolls and displays the results as a bar chart. Each die number from 1 to 6 gets its own bar. The higher the bar, the more frequently the corresponding number was rolled.

This creates a histogram that makes the statistical distribution of the results visible.


Central Variables

The program uses several variables to calculate statistics and display.

VariableMeaning
countsList of the number of rolls per die number
total_rollsTotal number of all rolls
MAX_BAR_HEIGHTMaximum Height of the Bars in the Diagram

The height of a bar is calculated relative to the most frequent die roll.


Control Panel

The simulation can be controlled both with the keyboard and with buttons in the window.

Keyboard

ButtonFunction
SPACESingle Die Roll
ASeries of Rolls
RReset Statistics
ESCExit Program

Buttons

At the bottom, there are three buttons:

ButtonFunction
+1One Roll
+10Ten Rolls
RSTReset

The buttons perform the same functions as the keyboard commands.


How a Die Roll is Counted

A die roll is generated with a random number. The corresponding position in the list counts is then increased.

1
2
3
w = random.randint(1, 6)
counts[w - 1] += 1
total_rolls += 1

Since lists in Python start at 0, the die value is reduced by 1.


Histogram Display

The bar height is calculated proportionally to the frequency.

1
2
3
4
def bar_height(value, max_value):
    if max_value == 0:
        return 0
    return int((value / float(max_value)) * MAX_BAR_HEIGHT)

This keeps the diagram well-scaled and independent of the number of rolls.

In addition, the program shows:


Expected Value

As soon as throws are available, an approximation of the expected value is calculated.

1
ev = sum((i + 1) * probs[i] for i in range(6))

This value approaches the theoretical value of a fair die with increasing numbers of throws.

The theoretical expected value is:

[ E = 3.5 ]


Tips for experimenting

This sandbox is intended to make your own observations.

Possible experiments:


Educational significance

This sandbox connects several subject areas:

Mathematics

Computer Science


As the number of throws increases, the observed distribution approaches the theoretical probability more closely.

The histogram thus makes a central concept in statistics visible: Law of large numbers.