CollatzConjecture
This is Documentation for the Julia package CollatzConjecture. For more background, check out this article Fun with Collatz Conjecture.
The Collatz Conjecture is a simple yet fascinating mathematical problem that asks: take any positive integer and repeatedly apply a basic rule until you reach 1. The rule is straightforward—if your number is even, divide it by 2; if it's odd, multiply by 3 and add 1. For example, starting with 7: 7 → 22 → 11 → 34 → 17 → 52 → 26 → 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1. The conjecture claims that no matter which positive integer you start with, you will always eventually reach 1. Despite its elementary appearance, this problem has stumped mathematicians for decades—while it has been verified by computers for incredibly large numbers, no one has been able to prove it's true for all positive integers, making it one of the most famous unsolved problems in mathematics.
The Collatz Function
Let $f: \mathbb{Z}^+ \to \mathbb{Z}^+$ be defined by:
\[f(n) = \begin{cases} \frac{n}{2} & \text{if } n \equiv 0 \pmod{2} \\ 3n + 1 & \text{if } n \equiv 1 \pmod{2} \end{cases}\]
where $\mathbb{Z}^+$ denotes the set of positive integers.
For any positive integer $n_0 \in \mathbb{Z}^+$, the Collatz sequence starting at $n_0$ is the sequence $(n_k)_{k=0}^{\infty}$ defined by:
\[n_{k+1} = f(n_k) \quad \text{for } k \geq 0\]
with initial condition $n_0$ given.
For a given starting value $n_0$, the stopping time $T(n_0)$ is defined as:
\[T(n_0) = \min\{k \geq 1 : n_k = 1\}\]
if such a $k$ exists, and $T(n_0) = \infty$ otherwise.
Conjecture: For every positive integer $n_0 \in \mathbb{Z}^+$, the stopping time $T(n_0)$ is finite.
Equivalently: For every $n_0 \in \mathbb{Z}^+$, there exists a finite $k$ such that $n_k = 1$.
Every orbit of the dynamical system defined by $f$ eventually reaches the fixed point 1. $\forall n_0 \in \mathbb{Z}^+ : \exists k \in \mathbb{N} \text{ such that } f^{(k)}(n_0) = 1$ where $f^{(k)}$ denotes the $k$-fold composition of $f$.
Remarks
The conjecture has been verified computationally for all $n_0 \leq 2^{68}$ (as of recent computational efforts).
The problem is equivalent to proving that the only cycle in the dynamical system is the trivial cycle $1 \to 4 \to 2 \to 1$.
The conjecture remains one of the most famous unsolved problems in mathematics, connecting elementary number theory with dynamical systems theory.
Visualizations
This package provides tools for exploring and visualizing the famous Collatz conjecture through various mathematical and artistic representations.
Quick Start
Here's a basic visualization of the first 25 Collatz sequences represented in the form of a tree.
using CollatzConjecture
using CairoMakie
CairoMakie.activate!()
fig_first_25 = create_collatz_with_labels(
n=25, label_fontsize=20,use_range = true,
s = 2.49, r = 0.76, h = 1.815, g = 1.3,
opacity = 0.93, # Lower opacity for many lines
e = 1.3, a = 0.19, f = 0.7,
label_color=:gray)

Fancy Visualizations
using CollatzConjecture
using CairoMakie
CairoMakie.activate!()
# Large set visualization
fig = create_collatz_visualization()
fig

Resources for getting started
There are a few ways to get started with CollatzConjecture:
Installation
Open a Julia session and enter
using Pkg; Pkg.add("CollatzConjecture")
this will download the package and all the necessary dependencies for you. Next you can import the package with
and you are ready to go.
Quickstart
using CollatzConjecture
CollatzConjecture.astro_intensity
— Methodastro_intensity(l, s, r, h, g)
Calculate RGB color values for astronomical intensity visualization.
This function computes RGB color values based on astronomical parameters using a mathematical transformation that combines lightness, saturation, and spectral characteristics. The calculation involves trigonometric functions and matrix-like operations to produce realistic color representations for astronomical data.
Arguments
l::Real
: Lightness parameter (typically in range [0,1])s::Real
: Saturation parameterr::Real
: Radial or spectral parameterh::Real
: Hue amplitude parameterg::Real
: Gamma correction exponent
Returns
Vector{Float64}
: RGB color values as a 3-element vector [R, G, B], clamped to [0,1]
Examples
julia> astro_intensity(0.5, 1.0, 0.2, 0.8, 2.0)
3-element Vector{Float64}:
0.4123
0.2847
0.6891
julia> astro_intensity(0.8, 0.5, 0.1, 1.2, 1.5)
3-element Vector{Float64}:
0.7234
0.5678
0.8901
julia> astro_intensity(0.2, 2.0, 0.5, 0.6, 1.8)
3-element Vector{Float64}:
0.1456
0.0892
0.3278
Notes
The function uses specific transformation coefficients optimized for astronomical color representation:
- Red channel: -0.14861 * cos(ψ) + 1.78277 * sin(ψ)
- Green channel: -0.29227 * cos(ψ) - 0.90649 * sin(ψ)
- Blue channel: 1.97294 * cos(ψ)
Where ψ = 2π * (s/3 + r * l) represents the phase angle for color calculation.
All output values are clamped to the valid color range [0,1].
CollatzConjecture.calculate_stopping_times
— Methodcalculate_stopping_times(max_n::Int)
Calculate stopping times for all integers from 1 to max_n
and return valid results.
This function computes the Collatz stopping time for each integer in the range [1, max_n] and returns only those numbers that have valid (positive) stopping times, filtering out any that exceed the safety limit or have invalid inputs.
Arguments
max_n::Int
: Maximum number to compute stopping times for (computes for range 1:max_n)
Returns
Tuple{Vector{Int}, Vector{Int}}
: A tuple containing:numbers
: Vector of numbers that have valid stopping timestimes
: Vector of corresponding stopping times (same length asnumbers
)
Examples
# Calculate stopping times for numbers 1-10
numbers, times = calculate_stopping_times(10)
# numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# times: [0, 1, 7, 2, 5, 8, 16, 3, 19, 6]
# Calculate for a larger range
numbers, times = calculate_stopping_times(100)
println("Number with longest stopping time: ", numbers[argmax(times)])
println("Maximum stopping time: ", maximum(times))
# Analyze the results
using Statistics
println("Mean stopping time: ", mean(times))
println("Median stopping time: ", median(times))
Details
The function processes each number sequentially:
- Calls
stopping_time(n)
for each n in 1:max_n - Filters results to include only positive stopping times
- Returns parallel arrays of numbers and their corresponding stopping times
Only numbers with valid stopping times are included in the results:
- Positive stopping times (successful convergence to 1)
- Excludes any numbers that return -1 (exceeded step limit)
- Excludes any numbers that return 0 (invalid inputs, though this shouldn't occur for positive integers)
Performance Considerations
- Time complexity: O(maxn × averagestopping_time)
- Space complexity: O(max_n) for storing results
- Memory efficient: Uses pre-allocated vectors that grow as needed
- Progress tracking: For large ranges, consider adding progress indicators
Use Cases
This function is particularly useful for:
- Statistical analysis of stopping time distributions
- Finding patterns in Collatz behavior across ranges
- Identifying outliers with unusually long stopping times
- Creating visualizations of stopping time data
- Research applications studying Collatz conjecture properties
Data Analysis Applications
# Find numbers with maximum stopping times
numbers, times = calculate_stopping_times(1000)
max_indices = findall(==(maximum(times)), times)
println("Numbers with maximum stopping time: ", numbers[max_indices])
# Create histogram of stopping times
using Plots
histogram(times, bins=50, title="Distribution of Stopping Times")
# Find correlation patterns
scatter(numbers, times, xlabel="Number", ylabel="Stopping Time")
Mathematical Insights
The resulting data can reveal:
- Distribution patterns in stopping times
- Record-breaking sequences (numbers with locally maximum stopping times)
- Power-of-2 patterns (2^k numbers have stopping time k)
- Statistical properties of the Collatz conjecture
See Also
stopping_time
: Calculate stopping time for a single numbercollatz_sequence
: Generate complete Collatz sequencescreate_collatz_visualization
: Visualize Collatz sequence patterns
CollatzConjecture.collatz_angle_path
— Methodcollatz_angle_path(n, e, a, f)
Generate a Collatz sequence and convert it to an angle-based path in Cartesian coordinates.
The function generates the Collatz sequence starting from n
, reverses it to begin from 1, then calculates radii and angles based on the sequence values to create a geometric path.
Arguments
n
: Starting number for the Collatz sequence (must be positive integer)e
: Exponent parameter for radius calculationa
: Angle scaling factorf
: Angle offset factor (typically used to distinguish even/odd behavior)
Returns
- Array of (x, y) coordinate tuples representing the path, starting from origin (0, 0)
Details
The path is constructed by:
- Generating the Collatz sequence from
n
to 1 - Reversing the sequence to start from 1
- Converting sequence values to radii using:
r = value / (1 + value^e)
- Calculating angles using:
angle = a * (f - 2 * (value % 2))
- Converting to Cartesian coordinates using cumulative angles and radii
Examples
path = collatz_angle_path(7, 0.5, π/4, 1.0)
CollatzConjecture.collatz_graph
— Functioncollatz_graph(range_end = 1000; kwargs...)
Create a directed graph visualization of Collatz sequences showing the relationships between numbers.
This function generates Collatz sequences for all numbers from 1 to range_end
, extracts the unique vertices and directed edges, and creates a graph visualization using GraphMakie.jl. The resulting graph shows how numbers transition to other numbers following Collatz rules.
Arguments
range_end = 1000
: Upper limit of the range (generates sequences for 1:range_end)
Keyword Arguments
Visual Styling
vertex_style = RGBA(44/51, 10/51, 47/255, 0.2)
: Color and transparency of graph verticesedge_style = RGB(38/255, 139/255, 14/17)
: Color of graph edgesvertex_size = 2
: Size of vertex markersedge_width = 0.5
: Width of edge lines
Layout and Structure
graph_layout = "ClosestPacking"
: Layout algorithm ("ClosestPacking", "Spring", or other)
Labels
show_labels = false
: Whether to show vertex labels with numberslabel_fontsize = 8
: Font size for vertex labels (only whenshow_labels=true
)
Output Control
print_stats = true
: Whether to print detailed statistics about the graph
Returns
Tuple{Figure, SimpleDiGraph, Vector{Int}, Vector{Tuple{Int,Int}}}
:fig
: Makie Figure containing the graph visualizationg
: The directed graph object from Graphs.jlvertices
: Vector of all unique vertices in the graphedges
: Vector of all directed edges as (source, destination) tuples
Examples
# Create basic Collatz graph for numbers 1-100
fig, graph, vertices, edges = collatz_graph(100)
# Create labeled graph for small range with custom styling
fig, graph, vertices, edges = collatz_graph(20,
show_labels = true,
vertex_size = 8,
label_fontsize = 10,
edge_width = 1.0
)
# Create large graph with spring layout
fig, graph, vertices, edges = collatz_graph(5000,
graph_layout = "Spring",
vertex_style = RGBA(1.0, 0.2, 0.2, 0.3),
print_stats = true
)
# Create minimal graph without statistics
fig, graph, vertices, edges = collatz_graph(50,
print_stats = false,
vertex_size = 1,
edge_width = 0.3
)
Details
The graph construction process:
- Sequence Generation: Creates Collatz sequences for all numbers 1 to
range_end
- Vertex Extraction: Collects all unique numbers that appear in any sequence
- Edge Extraction: Identifies directed transitions (n → next_n) from sequences
- Graph Building: Constructs a directed graph using Graphs.jl
- Connectivity Analysis: Analyzes connected components and graph structure
- Visualization: Creates a GraphMakie plot with specified styling and layout
The resulting graph reveals the structure of the Collatz conjecture, showing:
- How numbers flow through the conjecture's rules
- Connected components and convergence patterns
- The overall network structure of number relationships
Layout Options
"ClosestPacking"
: Uses stress-based layout for compact visualization"Spring"
: Uses spring-force layout for natural node spacing- Other layout algorithms supported by GraphMakie.jl
Performance Notes
- Labels are automatically disabled for graphs with >50 vertices for performance
- Progress indicators show generation status for large ranges
- Statistics provide insights into graph connectivity and structure
- Memory usage scales with the size of the largest numbers encountered
Graph Properties
The function analyzes and reports:
- Total number of unique vertices and edges
- Connected components and their sizes
- Vertex range (smallest to largest numbers)
- Presence of key vertices (powers of 2)
See Also
collatz_sequence
: Generate individual Collatz sequencescreate_collatz_visualization
: Create path-based visualizationscreate_collatz_tree
: Create tree-style visualizations
CollatzConjecture.collatz_graph_highlight_one
— Functioncollatz_graph_highlight_one(range_end = 1000; kwargs...)
Create a directed graph visualization of Collatz sequences with vertex 1 specially highlighted.
This function generates Collatz sequences for all numbers from 1 to range_end
, creates a graph visualization, and specially highlights vertex 1 (the convergence point of all Collatz sequences) with a distinct color, size, and label styling. All vertices can be optionally labeled to show their values.
Arguments
range_end = 1000
: Upper limit of the range (generates sequences for 1:range_end)
Keyword Arguments
Basic Graph Styling
vertex_style = RGBA(4/51, 51/51, 47/255, 0.8)
: Color and transparency of regular verticesedge_style = RGB(38/255, 139/255, 14/17)
: Color of graph edgesvertex_size = 2
: Size of regular vertex markersedge_width = 0.125
: Width of edge linesgraph_layout = "ClosestPacking"
: Layout algorithm ("ClosestPacking", "Spring", etc.)
Vertex 1 Highlighting
highlight_color = RGB(1.0, 0.2, 0.2)
: Color for vertex 1 (bright red by default)highlight_size = 15
: Size of vertex 1 marker (much larger than regular vertices)
Labeling Controls
show_all_labels = true
: Whether to show labels on all verticesmax_labeled_vertices = 50
: Maximum number of vertices to label (performance limit)label_fontsize = 14
: Font size for vertex labelsother_label_color = RGB(1.0, 1.0, 1.0)
: Color for labels on non-highlighted vertices
Output Control
print_stats = true
: Whether to print detailed statistics about the graph
Returns
Tuple{Figure, SimpleDiGraph, Vector{Int}, Vector{Tuple{Int,Int}}}
:fig
: Makie Figure containing the graph visualizationg
: The directed graph object from Graphs.jlvertices
: Vector of all unique vertices in the graphedges
: Vector of all directed edges as (source, destination) tuples
Examples
# Create highlighted graph with default settings
fig, graph, vertices, edges = collatz_graph_highlight_one(100)
# Create graph with custom highlight styling
fig, graph, vertices, edges = collatz_graph_highlight_one(50,
highlight_color = RGB(1.0, 1.0, 0.0), # Yellow highlight
highlight_size = 20,
label_fontsize = 12
)
# Create large graph with limited labeling
fig, graph, vertices, edges = collatz_graph_highlight_one(1000,
show_all_labels = true,
max_labeled_vertices = 100,
vertex_size = 1,
edge_width = 0.1
)
# Create minimal graph with only vertex 1 labeled
fig, graph, vertices, edges = collatz_graph_highlight_one(200,
show_all_labels = false,
vertex_style = RGBA(0.3, 0.3, 0.3, 0.5)
)
Details
The highlighting visualization process:
- Sequence Generation: Creates Collatz sequences for all numbers 1 to
range_end
- Graph Construction: Builds directed graph with vertices and edges
- Layout Computation: Calculates vertex positions using specified algorithm
- Special Highlighting: Identifies vertex 1 and applies special styling
- Layered Rendering: Draws edges first, then vertices, then labels for optimal appearance
- Smart Labeling: Labels all vertices up to the specified limit, with special styling for vertex 1
The function emphasizes the central role of vertex 1 in the Collatz conjecture by:
- Using a bright, contrasting color (red by default)
- Making vertex 1 significantly larger than other vertices
- Applying special label formatting (white text with black outline)
- Ensuring vertex 1 remains visible even in large graphs
Highlighting Features
- Vertex 1 Detection: Automatically locates and highlights vertex 1 if present
- Layered Rendering: Uses separate graph plot calls for edges and vertices for cleaner appearance
- Adaptive Labeling: Shows all labels up to the limit, but always prioritizes vertex 1's label
- Special Typography: Vertex 1 gets larger font size and enhanced stroke for visibility
Performance Considerations
- Labels are automatically limited to
max_labeled_vertices
for performance - For graphs exceeding the label limit, only vertex 1 is labeled
- Progress indicators show generation status for large ranges
- Memory usage scales with the largest numbers encountered in sequences
Visual Design
The function uses a layered approach:
- Transparent nodes with visible edges (base structure)
- Colored nodes on top (vertex highlighting)
- Text labels as the top layer (readability)
This ensures vertex 1's highlight is clearly visible while maintaining graph structure clarity.
See Also
collatz_graph
: Create standard Collatz graph without highlightingcollatz_sequence
: Generate individual Collatz sequencescreate_collatz_visualization
: Create path-based visualizationscreate_collatz_tree
: Create tree-style visualizations
CollatzConjecture.collatz_length
— Methodcollatz_length(n)
Calculate the length of the Collatz sequence for a given positive integer.
The Collatz sequence (also known as the 3n+1 problem or hailstone sequence) is generated by repeatedly applying the following rules:
- If the number is even: divide by 2
- If the number is odd: multiply by 3 and add 1
- Continue until reaching 1
This function counts the total number of steps in the sequence, including the final 1.
Arguments
n::Integer
: A positive integer to start the Collatz sequence
Returns
Integer
: The total length of the Collatz sequence (number of terms including the starting number and final 1)
Examples
julia> collatz_length(1)
1
julia> collatz_length(3)
8
julia> collatz_length(4)
3
julia> collatz_length(7)
17
julia> collatz_length(16)
5
Notes
The Collatz conjecture states that this sequence will always eventually reach 1 for any positive integer, though this has not been proven for all numbers.
CollatzConjecture.collatz_paths
— Methodcollatz_paths(numbers, e, a, f)
Generate Collatz angle paths for multiple starting numbers.
This is a vectorized version of collatz_angle_path
that processes multiple starting numbers simultaneously, returning an array of paths.
Arguments
numbers
: Collection of positive integers to use as starting values for Collatz sequencese
: Exponent parameter for radius calculation (applied to all paths)a
: Angle scaling factor (applied to all paths)f
: Angle offset factor (applied to all paths)
Returns
- Array of paths, where each path is an array of (x, y) coordinate tuples
Examples
# Generate paths for numbers 3, 5, and 7
paths = collatz_paths([3, 5, 7], 0.5, π/4, 1.0)
# Generate paths for a range of numbers
paths = collatz_paths(1:10, 0.3, π/6, 1.5)
CollatzConjecture.collatz_sequence
— Methodcollatz_sequence(n::Integer) -> Vector{Int}
Generate the complete Collatz sequence starting from a given positive integer.
The Collatz conjecture states that for any positive integer n, repeatedly applying the rule (n/2 if even, 3n+1 if odd) will eventually reach 1. This function returns the entire sequence from the starting number to 1.
Arguments
n::Integer
: Starting positive integer (must be > 0)
Returns
Vector{Int}
: Complete sequence from n to 1 (inclusive)
Examples
julia> collatz_sequence(3)
8-element Vector{Int64}:
3
10
5
16
8
4
2
1
julia> collatz_sequence(7)
17-element Vector{Int64}:
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
julia> length(collatz_sequence(27))
112
Notes
- The conjecture remains unproven, but has been verified for very large numbers
- Some sequences can become quite long before reaching 1
- The function will run indefinitely if the conjecture is false for the input
Throws
ArgumentError
: if n ≤ 0
See Also
- Wikipedia: Collatz conjecture
- OEIS A006577: Number of steps in Collatz sequence
CollatzConjecture.collatz_stopping_time
— Methodcollatz_stopping_time(n)
Calculate the stopping time of the Collatz sequence for a given positive integer.
The stopping time is the number of steps required to reach 1 from the starting number n in the Collatz sequence. The Collatz sequence is generated by repeatedly applying:
- If the number is even: divide by 2
- If the number is odd: multiply by 3 and add 1
- Continue until reaching 1
This function counts only the transformation steps, excluding the final 1.
Arguments
n::Integer
: A positive integer to start the Collatz sequence
Returns
Integer
: The number of steps required to reach 1 (stopping time)
Examples
julia> collatz_stopping_time(1)
0
julia> collatz_stopping_time(2)
1
julia> collatz_stopping_time(3)
7
julia> collatz_stopping_time(4)
2
julia> collatz_stopping_time(7)
16
julia> collatz_stopping_time(16)
4
Notes
The stopping time differs from sequence length by not counting the starting number or final 1. For example, the sequence 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 has stopping time 7.
See also: collatz_length
CollatzConjecture.complex_collatz
— MethodThe true complex Collatz map using the analytic continuation: T(z) = (1/4) * (2 + 7z - (2 + 5z) * cos(π*z))
This is the proper analytic continuation of the Collatz function to the complex plane.
CollatzConjecture.complex_collatz_alt
— MethodAlternative formulation using the Riemann sphere approach: T(z) = (1/2) * (z + 1 + (z - 1) * cos(π*z))
CollatzConjecture.complex_collatz_hybrid
— MethodAnother common complex Collatz formulation: T(z) = z/2 + (3z + 1)/4 * (1 - cos(π*z))
CollatzConjecture.create_collatz_tree
— Methodcreate_collatz_tree(; kwargs...)
Create a tree-like visualization of Collatz sequences as colored angle paths with vertex labels.
This function generates Collatz sequences, converts them to geometric paths, and creates a Makie.jl tree visualization with gradient colors and labeled vertices showing the actual Collatz numbers. The tree structure emphasizes the branching nature of Collatz sequences when visualized from their common convergence point.
Keyword Arguments
Color Parameters
s = 2.49
: Saturation parameter for color generationr = 0.76
: Red component parameter for color generationh = 1.815
: Hue parameter for color generationg = 1.3
: Green component parameter for color generationopacity = 0.5
: Transparency level for path lines (0.0 to 1.0)
Structure Parameters
e = 1.3
: Exponent parameter for radius calculation in path generationa = 0.19
: Angle scaling factor for path generationf = 0.7
: Angle offset factor for path generation
Number Selection
n = 5
: Number of sequences to generate (kept small for tree readability)use_range = false
: Whether to use a specific range instead of random numbersrange_start = 1
: Starting number for range (used whenuse_range = true
)range_end = 5000
: Ending number for range (used whenuse_range = true
)
Visualization Parameters
label_fontsize = 8
: Font size for vertex labelslabel_color = :white
: Color of vertex labelsshow_vertex_dots = true
: Whether to show dots at verticesvertex_size = 8
: Size of vertex dots/markersmax_label_length = 50
: Maximum number of labels per path (for long sequences)
Output Control
print_numbers = false
: Whether to print the numbers being processed
Returns
Figure
: A Makie.jl Figure object containing the tree visualization
Examples
# Create tree visualization with default parameters
fig = create_collatz_tree()
# Create tree for specific numbers with larger vertices
fig = create_collatz_tree(
use_range=true, range_start=10, range_end=15,
vertex_size=12, label_fontsize=10
)
# Create minimal tree without vertex dots
fig = create_collatz_tree(
n=3, show_vertex_dots=false, label_color=:cyan
)
# Create tree with custom structure parameters
fig = create_collatz_tree(
e=1.5, a=0.25, f=0.8, vertex_size=6
)
Details
The tree visualization process:
- Generates a set of numbers (smaller range for readability)
- Computes Collatz sequences and their corresponding angle paths
- Creates paths that emanate from a common origin (representing convergence to 1)
- Plots each branch as colored line segments with gradient colors
- Adds configurable vertex markers at sequence points
- Labels vertices with their corresponding Collatz numbers
- Uses black vertex dots to emphasize the tree structure
The tree structure becomes apparent as multiple Collatz sequences are displayed simultaneously, showing how different starting numbers create branching paths that all converge to the same point. The vertex_size
parameter allows for customization of the node prominence in the tree structure.
Notes
- Uses black vertex dots (instead of yellow) to emphasize tree node structure
- Vertex size is configurable to enhance tree visualization aesthetics
- Best viewed with smaller numbers of sequences (3-10) for clear tree structure
- All sequences share the common convergence point at the origin
See Also
create_collatz_with_labels
: Create labeled Collatz pathscreate_collatz_visualization
: Create unlabeled Collatz visualizationcollatz_paths
: Generate multiple Collatz angle pathsgenerate_path_colors
: Generate colors for path visualization
CollatzConjecture.create_collatz_visualization
— Methodcreate_collatz_visualization(; kwargs...)
Create a visualization of Collatz sequences as colored angle paths.
This function generates multiple Collatz sequences, converts them to geometric paths, and creates a Makie.jl visualization with gradient colors along each path.
Keyword Arguments
Color Parameters
s = 2.49
: Saturation parameter for color generationr = 0.76
: Red component parameter for color generationh = 1.815
: Hue parameter for color generationg = 1.3
: Green component parameter for color generationopacity = 0.5
: Transparency level for path lines (0.0 to 1.0)
Structure Parameters
e = 1.3
: Exponent parameter for radius calculation in path generationa = 0.19
: Angle scaling factor for path generationf = 0.7
: Angle offset factor for path generation
Number Selection
n = 300
: Number of random sequences to generate (used whenuse_range = false
)use_range = false
: Whether to use a specific range instead of random numbersrange_start = 5000
: Starting number for range (used whenuse_range = true
)range_end = 5020
: Ending number for range (used whenuse_range = true
)
Output Control
print_numbers = false
: Whether to print the numbers being processed
Returns
Figure
: A Makie.jl Figure object containing the visualization
Examples
# Create visualization with default parameters
fig = create_collatz_visualization()
# Create visualization with custom color parameters
fig = create_collatz_visualization(s=3.0, r=0.8, opacity=0.7)
# Create visualization for a specific range of numbers
fig = create_collatz_visualization(use_range=true, range_start=100, range_end=150)
# Create visualization with verbose output
fig = create_collatz_visualization(n=50, print_numbers=true)
Details
The visualization process:
- Generates a set of numbers (either random or from a specified range)
- Computes Collatz angle paths for each number
- Creates a transparent-background figure with hidden axes
- Plots each path as colored line segments with gradient colors
- Auto-scales the view to fit all paths
Each path is colored using the generate_path_colors
function with astronomical intensity mapping, creating smooth color transitions along the sequence.
CollatzConjecture.create_collatz_with_labels
— Methodcreate_collatz_with_labels(; kwargs...)
Create a visualization of Collatz sequences as colored angle paths with vertex labels.
This function generates Collatz sequences, converts them to geometric paths, and creates a Makie.jl visualization with gradient colors and labeled vertices showing the actual Collatz numbers at each point along the path.
Keyword Arguments
Color Parameters
s = 2.49
: Saturation parameter for color generationr = 0.76
: Red component parameter for color generationh = 1.815
: Hue parameter for color generationg = 1.3
: Green component parameter for color generationopacity = 0.5
: Transparency level for path lines (0.0 to 1.0)
Structure Parameters
e = 1.3
: Exponent parameter for radius calculation in path generationa = 0.19
: Angle scaling factor for path generationf = 0.7
: Angle offset factor for path generation
Number Selection
n = 5
: Number of sequences to generate (kept small for label readability)use_range = false
: Whether to use a specific range instead of random numbersrange_start = 1
: Starting number for range (used whenuse_range = true
)range_end = 5000
: Ending number for range (used whenuse_range = true
)
Label Parameters
label_fontsize = 8
: Font size for vertex labelslabel_color = :white
: Color of vertex labelsshow_vertex_dots = true
: Whether to show dots at verticesmax_label_length = 50
: Maximum number of labels per path (for long sequences)
Output Control
print_numbers = false
: Whether to print the numbers being processed
Returns
Figure
: A Makie.jl Figure object containing the labeled visualization
Examples
# Create labeled visualization with default parameters
fig = create_collatz_with_labels()
# Create visualization for specific numbers with custom labels
fig = create_collatz_with_labels(
use_range=true, range_start=7, range_end=12,
label_fontsize=10, label_color=:cyan
)
# Create visualization with fewer labels for cleaner appearance
fig = create_collatz_with_labels(
n=3, max_label_length=20, show_vertex_dots=false
)
# Create visualization with verbose output
fig = create_collatz_with_labels(n=5, print_numbers=true)
Details
The labeled visualization process:
- Generates a set of numbers (smaller range for readability)
- Computes Collatz sequences and their corresponding angle paths
- Creates a transparent-background figure with hidden axes
- Plots each path as colored line segments with gradient colors
- Adds vertex dots at sequence points (optional)
- Labels each vertex with its corresponding Collatz number
- For very long sequences, samples labels to maintain readability
The labeling system ensures that each Collatz number is positioned at its correct geometric location along the path. For sequences longer than max_label_length
, the function intelligently samples vertices while always including the first and last numbers.
Notes
- Uses smaller default numbers (10-100) compared to the unlabeled version for better readability
- Labels are offset slightly below vertices to avoid overlap with dots
- Very long sequences are automatically subsampled to prevent overcrowding
CollatzConjecture.create_complex_collatz_colormap
— MethodCreate enhanced colormap for the complex Collatz Julia set
CollatzConjecture.generate_complex_collatz_julia
— FunctionGenerate the complex Collatz Julia set
CollatzConjecture.generate_path_colors
— Methodgenerate_path_colors(path_length, s, r, h, g)
Generate colors for a path using astronomical intensity mapping.
Arguments
path_length
: Number of points in the paths
: Saturation parameter for astro_intensity functionr
: Red component parameter for astro_intensity functionh
: Hue parameter for astro_intensity functiong
: Green component parameter for astro_intensity function
Returns
- Array of RGB colors interpolated along the path length
Examples
colors = generate_path_colors(10, 0.8, 1.0, 0.5, 0.7)
CollatzConjecture.plot_collatz_fractal
— FunctionUnified plotting function for Complex Collatz Julia sets
CollatzConjecture.plot_collatz_julia
— FunctionUnified plotting function for Complex Collatz Julia sets
CollatzConjecture.plot_collatz_zoom
— FunctionZoom into a specific region of the Complex Collatz fractal
Parameters:
- centerx, centery: Complex coordinates for the center of the zoom
- zoomwidth, zoomheight: Width and height of the viewing window
- resolution: Image resolution (e.g., 800 = 800×800 pixels)
- max_iter: Maximum iterations for computation detail
- mapfunc: Which Collatz function to use (default: complexcollatz)
- title_suffix: Additional text for the plot title
Returns:
- fig: The generated figure
- julia_data: The computed fractal data matrix
CollatzConjecture.plot_stopping_times_histogram
— Functionplot_stopping_times_histogram(max_n::Int=1000)
Create a dual-axis histogram and cumulative distribution plot of Collatz stopping times.
This function calculates stopping times for all numbers from 1 to max_n
and creates a sophisticated visualization combining a frequency histogram (left y-axis) with a cumulative distribution function (right y-axis) to reveal both the distribution shape and cumulative probability patterns.
Arguments
max_n::Int=1000
: Maximum number to analyze (default: 1000)
Returns
Figure
: A Makie.jl Figure object containing the dual-axis histogram visualization
Examples
# Create default histogram for numbers 1-1000
fig = plot_stopping_times_histogram()
# Analyze distribution for smaller range with more detail
fig = plot_stopping_times_histogram(500)
# Study larger range to capture more statistical variation
fig = plot_stopping_times_histogram(10000)
# Save the analysis
save("stopping_times_distribution.png", fig)
Visualization Features
Histogram (Left Y-Axis)
- Blue bars: Frequency distribution of stopping times across 50 bins
- Black outlines: Clear bin boundaries for precise reading
- High transparency: 99% opacity for professional appearance
- Frequency counts: Left y-axis shows absolute number of occurrences
Cumulative Distribution (Right Y-Axis)
- Pink line: Cumulative distribution function (CDF) showing probability
- Smooth curve: Reveals percentile information and distribution shape
- Secondary axis: Right y-axis shows cumulative probability (0.0 to 1.0)
- Thick line: High visibility for trend analysis
Professional Styling
- Transparent background: Suitable for presentations and publications
- Large text: All labels use size 20 for excellent readability
- Color coordination: Blue for frequency, pink for probability
- Linked x-axes: Both plots share the same stopping time scale
Statistical Insights Revealed
Distribution Shape
- Skewness: Most stopping times are small, with a long right tail
- Modal behavior: Most common stopping times (highest bars)
- Outliers: Very large stopping times appear as sparse bins on the right
- Concentration: How stopping times cluster around typical values
Cumulative Patterns
- Percentiles: Easy to read what percentage of numbers have stopping times ≤ x
- Median identification: 50% cumulative probability point
- Quartiles: 25% and 75% probability thresholds
- Tail behavior: How quickly probability approaches 100%
Mathematical Applications
Research Analysis
# Compare distributions across different ranges
fig1 = plot_stopping_times_histogram(1000)
fig2 = plot_stopping_times_histogram(5000)
# Analyze how distribution shape changes with sample size
Educational Use
- Probability education: Demonstrates histogram vs. CDF concepts
- Statistical analysis: Shows real-world example of skewed distributions
- Collatz conjecture: Visualizes the unpredictable nature of stopping times
Technical Implementation
Histogram Computation
- Adaptive binning: Uses 50 bins automatically scaled to data range
- Frequency counting: Efficient computation of bin heights
- Professional styling: Consistent with statistical visualization standards
CDF Calculation
- Sorted processing: Efficiently computes cumulative probabilities
- Unique values: Handles repeated stopping times correctly
- Smooth interpolation: Creates visually appealing probability curve
Performance Characteristics
- Time complexity: O(n log n) due to sorting for CDF
- Space complexity: O(n) for storing computed values
- Memory efficient: Single-pass histogram computation
- Scalable: Handles large ranges (tested up to 100,000+)
Interpretation Guide
Reading the Histogram
- Peak locations: Most common stopping times
- Distribution width: Spread of typical stopping times
- Tail length: Range of extreme stopping times
Reading the CDF
- Steep sections: Ranges where many stopping times occur
- Flat sections: Ranges with few or no stopping times
- 50% point: Median stopping time
- 90% point: 90th percentile (most numbers have shorter stopping times)
Data Quality Features
- Automatic formatting: Integer labels for counts, decimal for probabilities
- Color coding: Distinct colors prevent confusion between axes
- Legend: Clear identification of the CDF line
- Professional presentation: Publication-ready styling
See Also
calculate_stopping_times
: Compute stopping times for analysisplot_stopping_times_scatter
: Scatter plot visualizationstopping_time
: Calculate individual stopping timescollatz_sequence
: Generate complete sequences
CollatzConjecture.plot_stopping_times_scatter
— Functionplot_stopping_times_scatter(max_n::Int=1000)
Create a scatter plot visualization of Collatz stopping times with a moving average trend line.
This function calculates stopping times for all numbers from 1 to max_n
and creates a scatter plot showing the relationship between starting numbers and their stopping times. A red moving average line reveals overall trends in the data.
Arguments
max_n::Int=1000
: Maximum number to analyze (default: 1000)
Returns
Figure
: A Makie.jl Figure object containing the scatter plot visualization
Examples
# Create default plot for numbers 1-1000
fig = plot_stopping_times_scatter()
# Plot for a smaller range with more detail
fig = plot_stopping_times_scatter(100)
# Plot for a larger range to see broader patterns
fig = plot_stopping_times_scatter(5000)
# Save the plot
save("stopping_times.png", fig)
Visualization Features
Scatter Plot Elements
- Blue points: Each point represents one number and its stopping time
- Transparency: Points have 90% opacity to show overlapping patterns
- Point size: Small markers (size 3) to avoid overcrowding
Trend Analysis
- Moving average: Red line showing smoothed trends across the data
- Window size: Automatically scaled as max_n ÷ 50 for appropriate smoothing
- Legend: Shows the moving average line identification
Styling
- Transparent background: Suitable for presentations and documents
- Large text: All labels and titles use size 20 for readability
- Professional formatting: Clean axis styling with appropriate tick formatting
Patterns Revealed
The visualization typically shows:
- Irregular spikes: Some numbers have much longer stopping times than neighbors
- General trends: Moving average reveals whether stopping times increase with number size
- Power-of-2 pattern: Numbers that are powers of 2 show predictable stepping
- Clustering effects: Groups of numbers with similar stopping times
- Outliers: Numbers with exceptionally long stopping times stand out clearly
Mathematical Insights
The plot helps identify:
- Record holders: Numbers with locally maximum stopping times
- Distribution shape: Whether stopping times follow any predictable pattern
- Growth behavior: How stopping times scale with input size
- Variance patterns: Regions of high vs. low variability
Technical Details
- Moving average calculation: Uses symmetric window around each point
- Window boundaries: Handles edge cases at the beginning and end of data
- Automatic scaling: Window size adapts to data range for optimal smoothing
- Memory efficient: Processes data in a single pass
Customization Options
While this function provides a standard visualization, you can modify the returned figure:
fig = plot_stopping_times_scatter(1000)
# Modify colors, add annotations, etc.
ax = fig[1, 1]
# Add additional analysis or annotations
Performance Notes
- Computation time scales with max_n
- For max_n > 10,000, consider computing in batches
- The moving average calculation is O(n) efficient
- Memory usage grows linearly with the number of data points
Use Cases
- Educational demonstrations of Collatz conjecture behavior
- Research analysis of stopping time patterns
- Statistical exploration of number theory properties
- Presentation graphics for mathematical talks
- Comparative analysis across different ranges
See Also
calculate_stopping_times
: Compute stopping times for analysisstopping_time
: Calculate individual stopping timescollatz_sequence
: Generate complete sequencescreate_collatz_visualization
: Alternative visualization approaches
CollatzConjecture.stopping_time
— Methodstopping_time(n::Int)
Calculate the stopping time (total number of steps) for a Collatz sequence starting from n
.
The stopping time is the number of iterations required for a Collatz sequence to reach 1. This function applies the standard Collatz rules: if n is even, divide by 2; if n is odd, multiply by 3 and add 1. The process continues until reaching 1.
Arguments
n::Int
: Starting positive integer for the Collatz sequence
Returns
Int
: Number of steps to reach 1, or special values:0
: If input is ≤ 0 (invalid input)-1
: If sequence exceeds 10,000 steps (potential infinite loop protection)
Examples
# Calculate stopping time for small numbers
stopping_time(1) # Returns 0 (already at 1)
stopping_time(2) # Returns 1 (2 → 1)
stopping_time(3) # Returns 7 (3 → 10 → 5 → 16 → 8 → 4 → 2 → 1)
stopping_time(4) # Returns 2 (4 → 2 → 1)
# Calculate stopping time for larger numbers
stopping_time(27) # Returns 111 (known to have a long sequence)
stopping_time(100) # Returns 25
# Edge cases
stopping_time(0) # Returns 0 (invalid input)
stopping_time(-5) # Returns 0 (invalid input)
Details
The function implements the standard Collatz conjecture iteration:
- If n is even: n → n/2
- If n is odd: n → 3n + 1
- Continue until n = 1
The stopping time provides insight into the complexity of different starting numbers:
- Powers of 2 have predictable stopping times: 2^k has stopping time k
- Odd numbers often have longer and less predictable stopping times
- Some numbers (like 27) are known to have surprisingly long sequences
Safety Features
- Input validation: Returns 0 for non-positive inputs
- Infinite loop protection: Returns -1 if more than 10,000 steps are required
- Overflow protection: Uses integer division to prevent unnecessary growth
Performance Notes
- Time complexity: O(s) where s is the stopping time
- Space complexity: O(1) - only tracks the current number and step count
- The 10,000 step limit prevents runaway computations while allowing most legitimate sequences
Mathematical Context
The stopping time is a key measure in Collatz conjecture research:
- The conjecture states that all positive integers eventually reach 1
- No counterexample has been found, but no proof exists
- Stopping times exhibit complex, seemingly chaotic behavior
- The distribution of stopping times is an active area of research
See Also
collatz_sequence
: Generate the complete Collatz sequencecollatz_angle_path
: Convert Collatz sequence to geometric pathcreate_collatz_visualization
: Visualize Collatz sequences
CollatzConjecture.test_collatz_connectivity
— Functiontest_collatz_connectivity(max_n = 20)
Test and analyze the connectivity of Collatz sequences for integers from 1 to max_n.
This function generates Collatz sequences for all integers from 1 to max_n and analyzes how they interconnect by finding shared vertices (numbers that appear in multiple sequences). It provides insights into the tree-like structure of the Collatz conjecture.
Arguments
max_n::Integer
: Maximum starting number to test (default: 20)
Returns
Tuple
: A tuple containing:sequences
: Vector of tuples (n, sequence) for each starting numbervertex_counts
: Dictionary mapping each vertex to the sequences that contain it
Examples
julia> sequences, vertex_counts = test_collatz_connectivity(5);
=== Testing Collatz sequence connectivity ===
1: [1] (length: 1)
2: [2, 1] (length: 2)
3: [3, 10, 5, 16, 8, 4, 2, 1] (length: 8)
4: [4, 2, 1] (length: 3)
5: [5, 16, 8, 4, 2, 1] (length: 6)
All unique vertices: [1, 2, 3, 4, 5, 8, 10, 16]
Shared vertices (vertex -> sequences that contain it):
1 appears in sequences: [1, 2, 3, 4, 5]
2 appears in sequences: [2, 3, 4, 5]
4 appears in sequences: [3, 4, 5]
8 appears in sequences: [3, 5]
16 appears in sequences: [3, 5]
julia> test_collatz_connectivity(10);
Notes
This function demonstrates the tree-like structure of Collatz sequences, where different starting numbers eventually merge into common paths. All sequences eventually reach 1, supporting the Collatz conjecture for the tested range.
The function requires collatz_sequence(n)
to be defined, which should return the complete Collatz sequence starting from n.
See also: collatz_sequence
, collatz_length
, collatz_stopping_time