Fun with AI: Random Thinking

Random Thinking

You said:

Write a Python script to seed the built in random number generator from the system clock, and generate 10,000 random numbers on the interval [00 to 99], writing them in a file in the current working directory. The Python script is to be named 10kRandom_A and the output file is to be named Random_Set_A.txt. The file is to contain each of the random numbers with a tab character following each number (except the last one).

Chat_GPT said:

The following Python script meets your specifications. It uses the system clock (nanosecond precision) to seed Python’s built-in random number generator.

Script filename: 10kRandom_A.py

Output filename: Random_Set_A.txt

import random
import time
from pathlib import Path
# Seed the random number generator from the system clock
random.seed(time.time_ns())
# Generate 10,000 random integers in the range 00 through 99
random_numbers = [random.randint(0, 99) for _ in range(10000)]
# Write the numbers to the output file in the current working directory
# Each number is formatted as two digits, with tabs between numbers
output_file = Path.cwd() / “Random_Set_A.txt”
with open(output_file, “w”) as file:
 file.write(“\t”.join(f”{number:02d}” for number in random_numbers))
print(f”10,000 random numbers written to: {output_file}”)

Specifications satisfied

1. Random number generator: Python’s built-in random module.

2. Seed: System clock using time.time_ns().

3. Quantity: Exactly 10,000 random integers.

4. Range: 00 through 99, inclusive.

5. Formatting: Every number occupies exactly two characters (including leading zeros).

6. Delimiter: One tab character between consecutive numbers.

7. Last number: No trailing tab character.

8. Output location: Current working directory.

9. Output filename: Random_Set_A.txt.

Execution: Save the script as 10kRandom_A.py and execute:

python 10kRandom_A.py

The output file will be created automatically in the directory from which you execute the script.

You said:

Write a Python script to do the following: First seed the built in random number generator from the system clock, and generate one random number on the interval [00 to 99], then re-seed the random number generator from the system clock and generate a second random number on the interval [00 to 99], and next re-seed the random number generator from the system clock and generate a third random number on the interval [00 to 99]. Thereafter, numbers are to be generated by summing the three immediately prior numbers and truncating the result to the last two (least signifcant) digits, such that they are on the interval [00 to 99]. This is to continue utill 10,000 number have been generated, and all of them written them in a file in the current working directory. The Python script is to be named 10kRandom_B and the output file is to be named Random_Set_B.txt. The file is to contain each of the random numbers with a tab character following each number (except the last one).

Chat_GPT said:

The following Python script implements your specified three-number recursive sequence.

Script filename: 10kRandom_B.py

Output filename: Random_Set_B.txt

import random
import time
from pathlib import Path
# Generate the first three numbers, independently seeded
numbers = []
for _ in range(3):
 random.seed(time.time_ns())
  numbers.append(random.randint(0, 99))
# Generate the remaining 9,997 numbers
# Each new number is the sum of the three preceding numbers,
# truncated to the last two digits.
while len(numbers) < 10000:
 next_number = sum(numbers[-3:]) % 100
 numbers.append(next_number)
# Write all 10,000 numbers to the output file
# Use two-digit formatting and tabs between numbers.
output_file = Path.cwd() / “Random_Set_B.txt”
with open(output_file, “w”) as file:
 file.write(“\t”.join(f”{number:02d}” for number in numbers))
print(f”10,000 numbers written to: {output_file}”)

Specifications satisfied

1. Initial number 1: Seed from the system clock and generate one random integer from 00 through 99.

2. Initial number 2: Reseed from the system clock and generate a second random integer.

3. Initial number 3: Reseed from the system clock and generate a third random integer.

4. Subsequent numbers: Add the three immediately preceding numbers and retain only the last two digits (% 100).

5. Total quantity: Exactly 10,000 numbers.

6. Formatting: Each number is written as two digits, including leading zeros.

7. Delimiter: One tab character between consecutive numbers, with no trailing tab after the final number.

8. Output location: Current working directory.

Sequence calculation

For illustration, suppose the first three numbers are:

23 41 68

The subsequent numbers would be:

Position Calculation Result

4 (23 + 41 + 68) % 100 32

5 (41 + 68 + 32) % 100 41

6 (68 + 32 + 41) % 100 41

7 (32 + 41 + 41) % 100 14

8 (41 + 41 + 14) % 100 96

Execution:

python 10kRandom_B.py

The script creates Random_Set_B.txt automatically in the current working directory.

You said:

Now, the last part. This one calls 10kRandom_B.py in its exectuion, and is to be named 10kRandom_C.py. For this one, create a Python script that generates three random numbers as before, re-seeding the system clock bewteen each, and thereafter generates more numbers as the sum of the preceeding three, with the sum truncated to the last two digits. However, this time, the last number is used as a reference pointer. That last two digit number is held, a new run of the same generator is started, but only until the position of the pointer is reached. That generated value is retained: written to the file Random_Set_C.txt. For example, suppose the work of 10kRandom_B.py generates a ten-thousand random number set, the last one of which is “86.” The process of 10kRandom_B.py is begun again, until the 86th value is obtained: that number, only, is placed into the random number output file. Then, the process is repeated. Another entirely new set of ten-thousand random numbers is generated, and for illustration suppose the last value is “33”. The 10kRandom_B.py process runs again, stopping when the thirty-third value is generated and that number, only, is placed into the random number output file. Should the last value in the random number set choosing the pointer be “01” or “02” or “03” then the first, second, or third value in the next generated set is selected for the random number output file. In the case that the last value in the in the random number set choosing the pointer comes out “00” this is interpreted as the one-hundredth position in the following random number generation. This process repeats until ten-thousand numbers, each the pointed-to location (with the pointer selected by a distinct ten thousand random number set) is generated and written to a file. As before, the numbers in the file Random_Set_C.txt are followed by a tab character, except the last one.

Chat_GPT said:

The third script will use 10kRandom_B.py as its pointer-generating program and produce Random_Set_C.txt.

There are two distinct random-number generations for each output number:

1. Pointer generation: Execute 10kRandom_B.py to generate a new set of 10,000 numbers. Retain its 10,000th (last) number as the pointer.

2. Selection generation: Start an entirely new sequence, using the same three-initial-seed and subsequent-addition procedure. Stop at the position specified by the pointer and retain that number.

3. Repeat this process until exactly 10,000 selected numbers have been collected.

The pointer interpretation is:

– 01 through 99 designate positions 1 through 99.

– 00 designates position 100.

The selection is one-based, so pointers 01, 02, and 03 select the first, second, and third numbers, respectively.

Python script: 10kRandom_C.py

The third script will use 10kRandom_B.py as its pointer-generating program and produce Random_Set_C.txt.

There are two distinct random-number generations for each output number:

1. Pointer generation: Execute 10kRandom_B.py to generate a new set of 10,000 numbers. Retain its 10,000th (last) number as the pointer.

2. Selection generation: Start an entirely new sequence, using the same three-initial-seed and subsequent-addition procedure. Stop at the position specified by the pointer and retain that number.

3. Repeat this process until exactly 10,000 selected numbers have been collected.

The pointer interpretation is:

– 01 through 99 designate positions 1 through 99.

– 00 designates position 100.

The selection is one-based, so pointers 01, 02, and 03 select the first, second, and third numbers, respectively.

Python script: 10kRandom_C.py

import random
import time
import subprocess
import sys
from pathlib import Path
# Locate the B script in the same directory as this script
script_dir = Path(__file__).resolve().parent
b_script = script_dir / “10kRandom_B.py”
# B’s output file is created in the current working directory
b_output = Path.cwd() / “Random_Set_B.txt”
c_output = Path.cwd() / “Random_Set_C.txt”
# Generate one new sequence and return the value at the
# specified one-based position.
def generate_selected_number(position):
# Start a completely new sequence with three independently
# clock-seeded random numbers.
  numbers = []
  for _ in range(3):
   random.seed(time.time_ns())
   numbers.append(random.randint(0, 99))
  # If the requested position is among the initial three,
  # return that number.
  if position <= 3:
   return numbers[position – 1]
  # Otherwise generate subsequent numbers using the
  # three immediately preceding numbers.
  while len(numbers) < position:
   next_number = sum(numbers[-3:]) % 100
   numbers.append(next_number)
  return numbers[-1]
# Collect exactly 10,000 selected numbers.
selected_numbers = []
for count in range(10000):
  # STEP 1:
  # Execute 10kRandom_B.py to generate a new 10,000-number set.
  subprocess.run(
   [sys.executable, str(b_script)],
   check=True
  )
  # STEP 2:
  # Read the last number from Random_Set_B.txt.
  with open(b_output, “r”) as file:
   pointer_set = file.read().split()
  pointer = int(pointer_set[-1])
  # STEP 3:
  # Interpret 00 as position 100.
  if pointer == 0:
   pointer = 100
  # STEP 4:
  # Generate a completely new sequence and select the
  # number at the pointer position.
  selected_number = generate_selected_number(pointer)
  # STEP 5:
  # Retain the selected number.
  selected_numbers.append(selected_number)
  if (count + 1) % 1000 == 0:
   print(f”{count + 1} of 10000 numbers generated.”)
# STEP 6:
# Write the 10,000 selected numbers to Random_Set_C.txt.
# Numbers are two digits, separated by tabs, with no
# trailing tab following the final number.
with open(c_output, “w”) as file:
  file.write(“\t”.join(f”{number:02d}” for number in selected_numbers))
print()
print(“Random_Set_C.txt successfully created.”)
print(f”Total numbers written: {len(selected_numbers)}”)
print(f”Output location: {c_output}”)

Important implementation details

Requirement Implementation

Pointer-generating program 10kRandom_B.py

Pointer source Last number of each B-generated set

Pointer range 01–99, with 00 interpreted as 100

Selection sequence Newly seeded, independent sequence

Selection algorithm Sum preceding three, modulo 100

Number of selections 10,000

Output file Random_Set_C.txt

Number formatting Two digits, including leading zeros

Separators Tabs, without a final trailing tab

Execution

All three scripts should be in the same directory:

10kRandom_A.py

10kRandom_B.py

10kRandom_C.py

Execute C with:

python 10kRandom_C.py

One performance consideration: This implementation executes B 10,000 separate times. Since each execution generates 10,000 numbers, that entails generating 100 million numbers for the pointer sets alone. The second sequence is generated only as far as its requested position, which can be at most 100.

Random_Set_B.txt will be overwritten each time B executes. Random_Set_C.txt will contain the final 10,000 selected numbers.

The implementation follows your specified selection procedure without changing the underlying B algorithm.

You said:

Clarification: at the end of execution, will Random_Set_B.txt remain, that being the last one run in the operation of 10kRandom_C.py?

Chat_GPT said:

Yes. At the end of 10kRandom_C.py, Random_Set_B.txt will remain in the current working directory, containing the 10,000-number set generated during the final execution of 10kRandom_B.py.

It is overwritten each time B runs, but it is not deleted by C.

You will therefore have both files:

– Random_Set_B.txt — the last complete 10,000-number set generated by B.

– Random_Set_C.txt — the 10,000 selected numbers produced by C.

You said:

Now we are ready to go to work. The overal point is to study randomness in various approaches to random number generation. The first attempt (A) is a straightforward random number generator as implemented by the Python language. The second attempt (B) seeks to use an innovative approach, essentially creating a new random number generator, seeding it with three starting values, and generating the remainder of the numbers therefrom. The third approach (C) employs this new approach an insanely large number of times, to create a set of random numbers. First question: which one do you think will exhibit the “most randomness” in the generated ten-thousand value number sets? Define “most random” and explain how you will test for this.

Chat_GPT said:

Studying the randomness of A, B, and C

This is an interesting experiment because the three approaches are fundamentally different. My initial prediction is that A will exhibit the greatest degree of randomness, followed by C, with B in third place. However, I would not regard that as a foregone conclusion. In particular, C is worth investigating because its behavior may be considerably less intuitive than either A or B.

Before testing, I want to establish an important principle:

Randomness is not the same thing as appearing unpredictable. A sequence can look thoroughly irregular to the human eye and nevertheless contain substantial mathematical structure.

Let’s establish what we mean by randomness and then develop a testing strategy.

1. What do we mean by “most random”?

For this experiment, I propose the following working definition:

A sequence is more random to the extent that its values:

– Are distributed uniformly across the available numbers (00–99).

– Exhibit no detectable relationship between successive values.

– Exhibit no detectable relationship between values separated by several positions.

– Contain no recurring patterns, cycles, or predictable structures.

– Behave consistently with an independent, uniformly distributed random sequence.

There is an important distinction here. A sequence can have an excellent distribution of individual values but still exhibit substantial dependence between consecutive values.

For example, suppose a generator produces all 100 possible numbers equally often. That sounds excellent. But suppose every number is followed by the number 37. Its frequency distribution might look perfect, but the sequence is obviously not random.

Consequently, we need several different tests.

2. My preliminary assessment of A, B, and C

A — Python’s built-in random generator

My expected winner

Python’s built-in random module uses the Mersenne Twister pseudorandom number generator.

It is a well-established algorithm designed to produce statistically convincing pseudorandom sequences.

Its principal characteristics:

– Very long period.

– Good statistical distribution.

– Good statistical independence properties for ordinary applications.

– Deterministic once its initial seed is established.

For our purposes, A provides an excellent baseline.

One qualification: Python’s generator is not a source of true physical randomness. It is a deterministic algorithm. Nevertheless, statistical quality and physical randomness are two different questions.

B — Three-number recursive generator

My expected weakest performer

Your approach is mathematically interesting:

Xn= ( Xn-1 + Xn-2 + Xn-3 ) mod 100

The first three numbers are randomly seeded, but every subsequent number is completely determined by those three initial values.

This creates several concerns.

1. The generator has a finite state space.

2. Its subsequent values are mathematically dependent on preceding values.

3. Its output may exhibit recurring patterns or periodicity.

4. Its distribution may not be uniform.

There is a particularly important consideration: because the recurrence operates modulo 100, the entire sequence is governed by a finite-state system. Once a state repeats, the subsequent sequence repeats.

This does not necessarily mean that a cycle will be short, but it does mean that the sequence cannot escape its deterministic structure.

C — Pointer-selected recursive generator

The interesting wild card

C is particularly interesting because it introduces another layer of selection.

For every output number:

1. B generates an entire 10,000-number sequence.

2. The last number becomes a pointer.

3. A new sequence is generated independently.

4. The pointer determines which position in that new sequence supplies the output number.

This changes the statistical characteristics considerably.

Unlike B, C does not simply output consecutive terms of one recursive sequence.

It effectively samples from many independently initialized recursive sequences, with the sampling position determined by another recursively generated sequence.

This could substantially reduce some of the visible sequential patterns found in B.

However, there is no guarantee that it produces a uniform distribution. The pointer itself may have a nonuniform distribution, and the selected values may also have a nonuniform distribution.

My prediction is that C will look more irregular than B, but whether it approaches A’s statistical quality is something we should measure rather than assume.

3. How I propose to test the three approaches

I would use five principal categories of statistical tests.

Test 1 — Frequency distribution

This is the most fundamental test.

For each 10,000-number set, count how many times each of the 100 possible numbers occurs.

If the generator is producing uniformly distributed values, we would expect:

10,000/100 = 100

occurrences of each number, on average.

We would construct a frequency table and examine the deviations from 100.

Illustrative example only

NumberABC
0098125103
011058796
02101112108
03967594
…………
9910211999

We will use the chi-square goodness-of-fit test to determine whether the observed frequency distributions depart significantly from uniformity.

A lower chi-square statistic generally indicates a closer fit to uniformity.

Test 2 — Sequential dependence

This is particularly important for B and C.

We will examine whether a number is statistically related to the number immediately preceding it.

For example:

– Does 23 occur disproportionately often after 41?

– Does a particular number tend to follow another particular number?

– Are certain transitions unusually common or unusually rare?

We can calculate serial correlations at multiple lags:

r1, r2, r3, … , r20

These measure relationships between numbers separated by one, two, three, and progressively more positions.

This test is especially important because B explicitly constructs every number from the preceding three numbers.

Test 3 — Runs and patterns

A run is a succession of values exhibiting some characteristic.

For example, consider the following sequence:

12 78 15 81 13 76 14 80

The values appear irregular, but there may be an underlying pattern.

We will examine:

– Runs of increasing and decreasing values.

– Runs above and below 50.

– Repeated numbers.

– Consecutive identical numbers.

– Unusually long sequences of similar values.

This will help identify patterns that a simple frequency distribution would miss.

Test 4 — Distribution of consecutive pairs

Rather than looking at individual numbers, we will examine combinations of two consecutive numbers.

There are 10,000 possible ordered pairs:

100 X 100 = 10,000th

For example:

12, 45

12, 46

12, 47

…

A sufficiently large sample should distribute these pairs in a manner consistent with independent uniform sampling.

Here, however, 10,000 observations are insufficient for a particularly powerful test because the expected frequency of each pair would be only one.

I would therefore use substantially larger samples for this particular investigation.

Test 5 — Entropy

Entropy measures the amount of uncertainty associated with a distribution.

For a perfectly uniform distribution of 100 possible values, the maximum Shannon entropy is:

The maximum is:

H = log2(100) ≈ 6.644 bits

We will calculate the observed entropy for A, B, and C.

However, there is an important qualification: high individual-number entropy does not establish independence. A sequence can have maximum individual-number entropy and still be highly predictable.

We should therefore also investigate conditional entropy, which measures how much uncertainty remains about the next number when preceding numbers are known.

4. How I would organize the experiment

I suggest we proceed in stages.

Stage 1 — Initial comparison

Generate one 10,000-number set each from A, B, and C.

First objective

– Frequency distribution

– Chi-square statistics

– Mean and standard deviation

– Entropy

– Serial correlations

Stage 2 — Repeated experiments

Generate 10 or more independent sets from each approach.

This is important because a single 10,000-number sample can produce misleading results simply through sampling variation.

Compare the average results and their variability.

Stage 3 — Larger samples

Generate 100,000 or 1,000,000 values from each approach.

This will help reveal patterns that may not be detectable in 10,000 values.

Stage 4 — More sophisticated testing

Investigate:

– Autocorrelation across multiple lags.

– Pair and triplet distributions.

– Runs tests.

– Conditional entropy.

– Periodicity and recurrence.

5. An important qualification concerning the experiment

There is one issue I want to make explicit before we begin.

All three approaches use the system clock to seed Python’s random number generator. That does not necessarily mean that the resulting seeds are independent or that the system clock supplies genuine entropy.

In particular, B and C repeatedly reseed their generators. We should be mindful of the clock’s actual resolution and the possibility of correlated seeds.

For the initial experiment, I recommend retaining your existing implementations exactly as written. We want to investigate the approaches you conceived, not modify them before understanding their behavior.

Later, we can investigate alternative seeding methods as a separate experiment.

6. My prediction

Here is my preliminary ranking:

Characteristic Expected first place

Uniformity of individual numbers A

Sequential independence A

Absence of detectable patterns A

Statistical entropy A or C

Resistance to recursive correlations A

My strongest prediction is that B will demonstrate identifiable mathematical structure.

C is the one I am most interested in examining. It may produce a much better-looking distribution than B, but that does not necessarily mean that it is statistically superior to A.

One final methodological point: We should not declare a winner merely because one sequence produces a lower chi-square statistic or higher entropy. We should look at the combined results of several independent tests, repeated across multiple generated sets. Statistical tests can fail to detect nonrandomness, and even genuinely random sequences sometimes produce apparently unusual results.

My proposed ultimate standard is this:

Which approach produces sequences whose statistical properties are hardest to distinguish from independently generated, uniformly distributed random numbers?

That is a question we can investigate scientifically, and I think your A/B/C experiment provides a very interesting starting point.

You said:

Okay. Here is the sceanario. In a Linux computer, there is a directory (the “current working directory.”) Inside that directory are three Python files (10kRandom_A.py, 10kRandom_B.py, and 10kRandom_C.py) along with three random number data sets (Random_Set_A.txt, Random_Set_B.txt, and Random_Set_C.txt). Write a Python driver script that will: (1) create a subdirectory named Trial001, and then run 10kRandom_A.py followed by 10kRandom_C.py, placing the output files Random_Set_A.txt, Random_Set_B.txt, and Random_Set_C.txt into the subdirectory Trial001. This will be repeated 100 times, such that there are at the conclusion one hundred subdirectories, Trial001, Trial002, Trial003, … Trial100, each of which contains three text files with ten-thousand random numbers each. These one hundred sample of Random_Set_A.txt can be combined, as wtih Random_Set_B.txt and Random_Set_c.txt files, to create a very large set of supposedly random numbers, to be studied. An important addendum is that the original directory, with the six files (three Python scripts and three data sets), is not to be touched. Write the top level Python driver now.

Chat_GPT said:

I recommend naming the driver script Run_Trials.py.

There is one important detail in the implementation: we will execute each experiment with its own trial directory as its working directory. This ensures that all generated data files go into the appropriate trial directory, while the original directory and its six existing files remain untouched.

The driver will:

1. Locate the three Python scripts in the original directory.

2. Create Trial001 through Trial100.

3. Run 10kRandom_A.py first.

4. Run 10kRandom_C.py second. C will call 10kRandom_B.py as part of its execution.

5. Leave all three resulting data files in the trial directory.

6. Repeat for all 100 trials.

An additional safeguard: if any of the 100 trial directories already exists, the driver will stop rather than overwrite existing work.

Run_Trials.py

import subprocess
import sys
from pathlib import Path
# The original directory containing the three Python scripts
# and the original data files.
root_dir = Path.cwd()
# Identify the three Python scripts.
script_A = root_dir / “10kRandom_A.py”
script_B = root_dir / “10kRandom_B.py”
script_C = root_dir / “10kRandom_C.py”
# Verify that all three scripts exist before starting.
for script in (script_A, script_B, script_C):
if not script.is_file():
  raise FileNotFoundError(f”Required script not found: {script}”)
# Check that none of the intended trial directories already exists.
for trial in range(1, 101):
  trial_dir = root_dir / f”Trial{trial:03d}”
if trial_dir.exists():
  raise FileExistsError(
f”{trial_dir} already exists. “
“No trials have been started.”
)
print(“Beginning 100 trials…”)
print()
# Execute the 100 trials.
for trial in range(1, 101):
  # Create the trial directory.
  trial_dir = root_dir / f”Trial{trial:03d}”
  trial_dir.mkdir()
  print(f”Starting Trial {trial:03d}…”)
  # Run A first, placing its output in the trial directory.
  subprocess.run(
   [sys.executable, str(script_A)],
   cwd=trial_dir,
   check=True
   )
  # Run C second.
  # C will automatically execute B as required.
  # All B and C output files will be placed in trial_dir.
  subprocess.run(
   [sys.executable, str(script_C)],
   cwd=trial_dir,
   check=True
   )
  # Verify that all three output files exist.
  expected_files = [
  “Random_Set_A.txt”,
  “Random_Set_B.txt”,
  “Random_Set_C.txt”
  ]
  for filename in expected_files:
   output_file = trial_dir / filename
  if not output_file.is_file():
   raise FileNotFoundError(
  f”Expected output missing: {output_file}”
  )
print(f”Trial {trial:03d} completed.”)
print()
print(“=” * 45)
print(“ALL 100 TRIALS COMPLETED SUCCESSFULLY”)
print(“=” * 45)
print()
print(f”Trial directories created: 100″)
print(f”Location: {root_dir}”)
print(“Each directory contains three 10,000-number files.”)

Expected directory structure

Original Directory/

|

|– 10kRandom_A.py

|– 10kRandom_B.py

|– 10kRandom_C.py

|– Run_Trials.py

|

|– Random_Set_A.txt (original, untouched)

|– Random_Set_B.txt (original, untouched)

|– Random_Set_C.txt (original, untouched)

|

|– Trial001/

| |– Random_Set_A.txt

| |– Random_Set_B.txt

| |– Random_Set_C.txt

|

|– Trial002/

| |– Random_Set_A.txt

| |– Random_Set_B.txt

| |– Random_Set_C.txt

|

| …

|

|– Trial100/

|– Random_Set_A.txt

|– Random_Set_B.txt

|– Random_Set_C.txt

Execution

From the original directory, execute:

python Run_Trials.py

Two important observations

1. Protection of original files

The original six files are never opened for writing. All three programs execute with their respective trial directory as their working directory. Even though C calls B, B’s output also goes into that trial directory.

2. Execution time

There is a potentially significant performance issue. Your current C program launches B as a separate Python process 10,000 times per trial. Across 100 trials, that means 1,000,000 executions of B.

The driver faithfully follows your specifications, but this could take a very long time.

I recommend that we eventually optimize C without changing its mathematical algorithm. That would make the 100-trial experiment considerably more practical.

The experimental design itself is sound: you will have 100 independent samples of 10,000 values each, for a total of 1,000,000 observations per method. This gives us a much more substantial foundation for comparing A, B, and C.

I must be off to patrol the moat.