Computer Programming, Numerical Algorithms, and Number Systems 10/13

Iteration, Range, and the Harmonic Series

  • Nested Loops and Grid Traversal:

    • Multi-dimensional data processing relies heavily on nested loops to traverse rows and columns.

    • Outer loops typically govern row progression, while inner loops sweep through columns (e.g., beginning at row 11, then traversing column 11, column 22, column 33, up through column 1010).

  • Harmonic Series Definition and Approximation:

    • The harmonic series is an infinite summation defined mathematically as:∑k=1n1k=1+12+13+⋯+1n\sum_{k=1}^{n} \frac{1}{k} = 1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}

    • The value of this summation grows logarithmically and is analytically approximated using the natural logarithm ln⁡(n)\ln(n).

  • Variable Initialization and Type Rigor:

    • Accumulator variables for sums must be initialized explicitly as floating-point literals (e.g., total = 0.0).

    • Initializing with 0 instead of 0.0 creates implicit integer types. While high-level dynamically typed interpreters such as Python may perform implicit type coercion, strictly typed systems (such as C or C++) experience severe semantic or type errors if floating-point accumulation is initialized to an integer.

  • Mechanics of the range() Function:

    • The range() function accepts up to three integer arguments: range(start, end, step).

    • Parameter ordering rules:

    • Single argument: range(end) — Defaults start to 00 and step to 11. The sequence runs from 00 to end−1\text{end} - 1.

    • Two arguments: range(start, end) — Defaults step to 11. The sequence runs from start to end−1\text{end} - 1.

    • Three arguments: range(start, end, step) — Generates numbers starting at start, incrementing by step, and terminating strictly before end.

    • Interval inclusivity: The start parameter is inclusive, whereas the end parameter is strictly exclusive.

    • For accumulating an nn-term sequence such as the harmonic series, the range is specified as range(1, n + 1) with a step size of 11.

    • Starting the iteration at index 11 rather than 00 is mandatory: evaluating 1k\frac{1}{k} when k=0k = 0 results in an undefined division by zero error (ZeroDivisionError\text{ZeroDivisionError}).

Numerical Approximation: Newton's Method for Square Roots

  • Formulation of Newton's Method:

    • Newton's method (the Newton-Raphson method) calculates the square root of a non-negative constant cc through repeated algebraic approximations.

    • Given an initial estimate tt, the successive value is recalculated iteratively using the formula:t=ct+t2t = \frac{\frac{c}{t} + t}{2}

  • Convergence Threshold and Epsilon:

    • Because floating-point representations cannot achieve infinite exactness, convergence is bounded by a predefined tolerance parameter, epsilon (ϵ\epsilon).

    • Standard scientific notation for epsilon is defined as a constant:ϵ=1×10−15=1e-15\epsilon = 1 \times 10^{-15} = 1\text{e-}15

    • The iteration continues while the absolute error between the current estimate and the true square root exceeds ϵ\epsilon:∣t−ct∣>ϵ\left| t - \frac{c}{t} \right| > \epsilon

    • Absolute values must be taken to guarantee non-negative comparisons against ϵ\epsilon.

  • Command-Line Program Execution:

    • Command-line arguments in Python are accessed via system libraries (sys.argv).

    • sys.argv[0] is reserved for the file name of the script being executed (e.g., sqrt.py inside the introcs or IPP directory).

    • sys.argv[1] captures the first user-supplied runtime argument passed into the program (e.g., calculating 2\sqrt{2} by executing with an input of 22).

  • Floating-Point Precision Limits and Infinite Loops:

    • Standard 64-bit IEEE 754 floating-point numbers provide up to 1515 decimal digits of precision.

    • Attempting to compute convergence beyond 1515 decimal digits (such as 1616 decimal places) causes computational failure: the variable tt repeats identical values across successive iterations.

    • When the machine precision cannot represent smaller differences, the condition never drops below the tighter threshold, locking the program into an infinite loop.

    • While languages like C and Java provide extended data types (such as double, double double, or long long) with larger bit depths, hardware-level limitations still introduce rounding errors and overflow.

Number Systems: Decimal to Binary Conversion Principles

  • Positional Number System Foundations:

    • Base-10 (decimal) is assumed by default in numerical notation unless indicated otherwise by subscript bases (e.g., base-16 denoting hexadecimal).

    • Base-2 (binary) uses two discrete binary digits: 00 and 11.

    • Binary digits must always be pronounced and read individually (e.g., 10210_2 is read as "one zero", never as "ten"; 1002100_2 is read as "one zero zero", never as "one hundred").

  • Elementary Decimal-to-Binary Mapping:

    • 010=020_{10} = 0_2

    • 110=121_{10} = 1_2

    • 210=1022_{10} = 10_2

    • 310=1123_{10} = 11_2

    • 410=10024_{10} = 100_2

    • 510=10125_{10} = 101_2

    • 610=11026_{10} = 110_2

    • 710=11127_{10} = 111_2

    • Advancing sequential binary values operates by adding 11 to the least significant bit (LSB) and propagating carries toward the most significant bit (MSB).

  • Bit Significance (MSB vs. LSB):

    • Least Significant Bit (LSB): The rightmost digit, corresponding to the positional weight 20=12^0 = 1.

    • Most Significant Bit (MSB): The leftmost digit, corresponding to the highest positional power 2k2^k.

    • Real-world positional value analogy: In decimal monetary notation, the relative arrangement of digits dramatically alters magnitude (e.g., earning $1,999,999\$1,999,999 where the leftmost digit carries millions, versus earning $999,991\$999,991 or $099\$099 versus $990\$990).

    • Binary evaluation example comparing 111021110_2 and 011120111_2:11102=(1×23)+(1×22+(1×21)+(0×20)=8+4+2+0=14101110_2 = (1 \times 2^3) + (1 \times 2^2 + (1 \times 2^1) + (0 \times 2^0) = 8 + 4 + 2 + 0 = 14_{10}

Iteration, Range, and the Harmonic Series
  • Nested Loops and Grid Traversal:

    • Multi-dimensional data processing relies heavily on nested loops to traverse rows and columns.

    • Outer loops typically govern row progression, while inner loops sweep through columns (e.g., beginning at row 11, then traversing column 11, column 22, column 33, up through column 1010).

  • Harmonic Series Definition and Approximation:

    • The harmonic series is an infinite summation defined mathematically as:
      ∑k=1n1k=1+12+13+⋯+1n\sum_{k=1}^{n} \frac{1}{k} = 1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}

    • The value of this summation grows logarithmically and is analytically approximated using the natural logarithm ln⁡(n)\ln(n).

  • Variable Initialization and Type Rigor:

    • Accumulator variables for sums must be initialized explicitly as floating-point literals (e.g., total = 0.0).

    • Initializing with 0 instead of 0.0 creates implicit integer types. While dynamically typed interpreters such as Python may perform implicit type coercion, strictly typed systems (such as C or C++) experience severe semantic or type errors if floating-point accumulation is initialized to an integer.

  • Mechanics of the range() Function:

    • The range() function accepts up to three integer arguments: range(start, end, step).

    • Parameter ordering rules:

    • Single argument: range(end) defaults start to 00 and step to 11. The sequence runs from 00 to end−1\text{end} - 1.

    • Two arguments: range(start, end) defaults step to 11. The sequence runs from start to end−1\text{end} - 1.

    • Three arguments: range(start, end, step) generates numbers starting at start, incrementing by step, and terminating strictly before end.

    • Interval inclusivity: The start parameter is inclusive, whereas the end parameter is strictly exclusive.

    • For accumulating an nn-term sequence such as the harmonic series, the range is specified as range(1, n + 1) with a step size of 11.

    • Starting the iteration at index 11 rather than 00 is mandatory: evaluating 1k\frac{1}{k} when k=0k = 0 results in an undefined division by zero error (ZeroDivisionError).

Numerical Approximation: Newton's Method for Square Roots
  • Formulation of Newton's Method:

    • Newton's method (the Newton-Raphson method) calculates the square root of a non-negative constant cc through repeated algebraic approximations.

    • Given an initial estimate tt, the successive value is recalculated iteratively using the formula:
      t=ct+t2t = \frac{\frac{c}{t} + t}{2}

  • Convergence Threshold and Epsilon:

    • Because floating-point representations cannot achieve infinite exactness, convergence is bounded by a predefined tolerance parameter, epsilon (ϵ\epsilon).

    • Standard scientific notation for epsilon is defined as a constant:
      ϵ=1×10−15=1e-15\epsilon = 1 \times 10^{-15} = 1\text{e-}15

    • The iteration continues while the absolute error between the current estimate and the true square root exceeds ϵ\epsilon:
      ∣t−ct∣>ϵ\left| t - \frac{c}{t} \right| > \epsilon

    • Absolute values must be taken to guarantee non-negative comparisons against ϵ\epsilon.

  • Command-Line Program Execution:

    • Command-line arguments in Python are accessed via the system library (sys.argv).

    • sys.argv[0] is reserved for the file name of the script being executed (e.g., sqrt.py inside the introcs or IPP directory).

    • sys.argv[1] captures the first user-supplied runtime argument passed into the program (e.g., calculating 2\sqrt{2} by executing with an input of 22).

  • Floating-Point Precision Limits and Infinite Loops:

    • Standard 64-bit IEEE 754 floating-point numbers provide up to 1515 decimal digits of precision.

    • Attempting to compute convergence beyond 1515 decimal digits (such as 1616 decimal places) causes computational failure: the variable tt repeats identical values across successive iterations.

    • When the machine precision cannot represent smaller differences, the condition never drops below the tighter threshold, locking the program into an infinite loop.

    • While languages like C and Java provide extended data types (such as double, double double, or long long) with larger bit depths, hardware-level limitations still introduce rounding errors and overflow.

Number Systems: Decimal-to-Binary Conversion Principles
  • Positional Number System Foundations:

    • Base-10 (decimal) is assumed by default in numerical notation unless indicated otherwise by subscript bases (e.g., base-16 denoting hexadecimal).

    • Base-2 (binary) uses two discrete binary digits: 00 and 11.

    • Binary digits must always be pronounced and read individually (e.g., 10<em>210<em>2 is read as "one zero", never as "ten"; 100</em>2100</em>2 is read as "one zero zero", never as "one hundred").

  • Elementary Decimal-to-Binary Mapping:

    • 0<em>10=0</em>20<em>{10} = 0</em>2

    • 1<em>10=1</em>21<em>{10} = 1</em>2

    • 2<em>10=10</em>22<em>{10} = 10</em>2

    • 3<em>10=11</em>23<em>{10} = 11</em>2

    • 4<em>10=100</em>24<em>{10} = 100</em>2

    • 5<em>10=101</em>25<em>{10} = 101</em>2

    • 6<em>10=110</em>26<em>{10} = 110</em>2

    • 7<em>10=111</em>27<em>{10} = 111</em>2

    • Advancing sequential binary values operates by adding 11 to the least significant bit (LSB) and propagating carries toward the most significant bit (MSB).

  • Bit Significance (MSB vs. LSB):

    • Least Significant Bit (LSB): The rightmost digit, corresponding to the positional weight 20=12^0 = 1.

    • Most Significant Bit (MSB): The leftmost digit, corresponding to the highest positional power 2k2^k.

    • Positional value analogy: In decimal notation, digit arrangement drastically alters magnitude (e.g., earning $1,999,999\$1{,}999{,}999 where the leftmost digit carries millions, versus earning $999,991\$999{,}991, or $099\$099 versus $990\$990).

    • Binary evaluation example comparing 1110<em>21110<em>2 and 0111</em>20111</em>2:
      1110<em>2=(1×23)+(1×22)+(1×21)+(0×20)=8+4+2+0=14</em>101110<em>2 = (1 \times 2^3) + (1 \times 2^2) + (1 \times 2^1) + (0 \times 2^0) = 8 + 4 + 2 + 0 = 14</em>{10}
      0111<em>2=(0×23)+(1×22)+(1×21)+(1×20)=0+4+2+1=7</em>100111<em>2 = (0 \times 2^3) + (1 \times 2^2) + (1 \times 2^1) + (1 \times 2^0) = 0 + 4 + 2 + 1 = 7</em>{10}

  • Manual Powers-of-Two Decomposition Method:

    • Identify the largest power of two that fits inside the target decimal value, assign a 11 at that bit position, subtract that power from the value, and evaluate subsequent descending powers.

    • Decomposing 9109_{10}:

    • Highest power fitting in 99 is 23=82^3 = 8. Bit position 33 is set to 11.

    • Remaining value: 9−8=19 - 8 = 1.

    • Powers 22=42^2 = 4 and 21=22^1 = 2 do not fit into 11, so bit positions 22 and 11 are set to 00.

    • Power 20=12^0 = 1 fits into 11, setting bit position 00 to 11.

    • Result: 100121001_2.

    • Decomposing 171017_{10}:

    • Largest power is 24=162^4 = 16, leaving 17−16=117 - 16 = 1.

    • Bits for 23,22,212^3, 2^2, 2^1 evaluate to 00, and 202^0 evaluates to 11.

    • Result: 10001210001_2.

    • Decomposing 181018_{10}:

    • 16+2=(1×24)+(0×23)+(0×22)+(1×21)+(0×20)=10010216 + 2 = (1 \times 2^4) + (0 \times 2^3) + (0 \times 2^2) + (1 \times 2^1) + (0 \times 2^0) = 10010_2.

  • Repeated Division Method (Quotient-Remainder Technique):

    • Continuously divide the decimal integer by 22, record each integer quotient and remainder, and read the remainders in reverse order (from bottom to top).

    • Example: Converting 191019_{10} to binary:

    • 19÷2=919 \div 2 = 9 remainder 11

    • 9÷2=49 \div 2 = 4 remainder 11

    • 4÷2=24 \div 2 = 2 remainder 00

    • 2÷2=12 \div 2 = 1 remainder 00

    • 1÷2=01 \div 2 = 0 remainder 11

    • Reading remainders in reverse order yields: 10011210011_2.

Algorithmic Implementation of Decimal-to-Binary Conversion
  • Mathematical Floor and Ceiling Operations:

    • Floor Division (⌊x⌋\lfloor x \rfloor): Rounds a real value down to the nearest integer.

    • ⌊3.9⌋=3\lfloor 3.9 \rfloor = 3

    • ⌊3.99⌋=3\lfloor 3.99 \rfloor = 3

    • ⌊2.999⌋=2\lfloor 2.999 \rfloor = 2

    • Integer floor division of 19//219 // 2 produces 99 (discarding the fractional remainder 0.50.5).

    • Ceiling (⌈x⌉\lceil x \rceil): Rounds a real value up to the nearest integer.

    • ⌈3.99⌉=4\lceil 3.99 \rceil = 4

    • ⌈4.1⌉=5\lceil 4.1 \rceil = 5

  • Step-by-Step Binary Extraction Algorithm:

    • The algorithm takes a positive integer nn and extracts binary digits from left to right using two sequential, non-nested while loops.

    • Phase 1: Finding the Highest Power of Two (vv)

    • Initialize the power tracker: v = 1.

    • Loop condition: while v <= n // 2: with update v = v * 2.

    • For n=19n = 19, the threshold is 19//2=919 // 2 = 9.

    • Iteration progression:

      • v=1≤9→vv = 1 \le 9 \rightarrow v becomes 22

      • v=2≤9→vv = 2 \le 9 \rightarrow v becomes 44

      • v=4≤9→vv = 4 \le 9 \rightarrow v becomes 88

      • v=8≤9→vv = 8 \le 9 \rightarrow v becomes 1616

      • Next check: 16≤916 \le 9 is false; loop terminates with v=16v = 16.

    • Phase 2: Extracting Digits and Reducing (v>0v > 0)

    • Loop condition: while v > 0:

    • Inside the loop:

      • If n<vn < v, output 0.

      • Else, output 1 and update n=n−vn = n - v.

      • Halve the bit tracker: v = v // 2 (executed on every iteration outside the if-else block).

    • Trace for n=19n = 19 and v=16v = 16:

    • Step 1: n=19n = 19, v=16v = 16. Condition 19<1619 < 16 is false. Output 1, set n=19−16=3n = 19 - 16 = 3, set v = 16 // 2 = 8.

    • Step 2: n=3n = 3, v=8v = 8. Condition 3<83 < 8 is true. Output 0, set v = 8 // 2 = 4.

    • Step 3: n=3n = 3, v=4v = 4. Condition 3<43 < 4 is true. Output 0, set v = 4 // 2 = 2.

    • Step 4: n=3n = 3, v=2v = 2. Condition 3<23 < 2 is false. Output 1, set n=3−2=1n = 3 - 2 = 1, set v = 2 // 2 = 1.

    • Step 5: n=1n = 1, v=1v = 1. Condition 1<11 < 1 is false. Output 1, set n=1−1=0n = 1 - 1 = 0, set v = 1 // 2 = 0.

    • Step 6: v=0v = 0. Loop condition 0 > 0 is false; loop terminates.

    • Resulting output sequence: 10011.

  • Syntactic Scope Differences: Python vs. C/Java:

    • In Python, block scope is dictated strictly by indentation. The statement v = v // 2 must not be indented under the else block; it sits directly inside the while block so that the power of two divides on every step.

    • In C and Java, explicit curly braces ({}) delimit code blocks, eliminating ambiguity about conditional scope.

Command Line Navigation and Environment Operations
  • Core Unix/Terminal Navigation Commands:

    • pwd: Prints the working directory path (e.g., verifying the current path /workspace/control_flow).

    • ls: Lists all files and directories in the active directory.

    • cd: Changes the active working directory.

  • Directory Hierarchy Traversal:

    • .. denotes the parent directory relative to the current position.

    • Navigating to a sibling directory (such as moving from control_flow to IPP under the parent /workspace):

    • Running cd IPP directly fails because IPP is not inside control_flow.

    • Correct relative path command: cd ../IPP (moves up to the parent directory, then enters sibling directory IPP).

Software Engineering Realities and Artificial Intelligence Limitations
  • Case Study: EEG Brainwave Signal Processing:

    • In an EEG headset project capturing brainwaves for computer action controls, electrodes mounted across the headband produced varying impedances and signal ranges.

    • Large Language Models (LLMs) failed to classify the signals because they analyzed raw scalar ranges rather than wave morphology.

    • Solution: Raw scalar sequences (1.1,1.2,1.31.1, 1.2, 1.3) were converted into graphical sinusoidal wave representations and classified using a Convolutional Neural Network (CNN).

    • Human software architecture and domain knowledge remain indispensable for diagnosing edge cases and guiding automated tools.

  • Empirical Code Quality and Redundancy:

    • Research indicates that 20%20\% to 30%30\% of code generated by generative AI models contains redundant or non-functional logic that can be removed without altering behavior.

  • Software Engineering vs. Code Generation:

    • The primary bottleneck in software engineering is long-term maintenance, debugging, edge-case mitigation, performance optimization, and security patching—not initial code synthesis.

    • Enterprise codebases regularly consist of hundreds of thousands of files and millions of lines of code.

    • Refactoring and fixing existing code is significantly harder than writing new scripts from scratch.

    • Relying exclusively on AI threatens developer training: bypassing junior developers eliminates the development pipeline needed to produce experienced senior architects.

Monte Carlo Simulation: Gambler's Ruin Problem
  • Problem Formulation:

    • Scenario: A gambler begins with a starting stake and places repeated, fair 11-dollar wagers until either going broke (cash=0\text{cash} = 0, ruin) or reaching a target balance (cash=goal\text{cash} = \text{goal}, victory).

    • Simulation Inputs:

    • stake: Initial cash balance brought to each trial (integer, e.g., $20\$20).

    • goal: Target cash amount to achieve (integer, e.g., $30\$30).

    • trials: Number of independent, simulated games to run (integer, e.g., 10,00010{,}000).

    • Tracked Aggregate Metrics:

    • bets: Total number of individual wagers placed across all trials.

    • wins: Total number of trials that successfully ended with cash == goal.

  • Algorithmic Simulation Logic:

    • Outer loop iterates through each trial using range(trials) with index t running from 00 to trials−1\text{trials} - 1.

    • Within each trial:

    • Reset cash to the starting stake: cash = stake.

    • Run an inner simulation loop while the player has money and has not reached the goal: while cash > 0 and cash < goal:

      • Increment total bets: bets += 1.

      • Simulate a fair coin toss using stdrandom.bernoulli(0.5):

      • If successful (True), add 11 dollar: cash += 1.

      • If unsuccessful (False), subtract 11 dollar: cash -= 1.

    • Once the inner loop terminates, update the win counter using an inline conditional:

      • wins += 1 if cash == goal else 0

  • Output Metric Calculations:

    • Win Percentage: Measures the empirical fraction of trials that ended in reaching the goal balance:
      Win Percentage=(winstrials)×100\text{Win Percentage} = \left( \frac{\text{wins}}{\text{trials}} \right) \times 100

    • Average Bets per Trial: Measures the expected duration of each game:
      Average Bets=betstrials\text{Average Bets} = \frac{\text{bets}}{\text{trials}}

    • Running large sample sizes (e.g., stake = $20\$20, goal = $30\$30, trials = 10,00010{,}000) provides empirical convergence toward analytical Gambler's Ruin probabilities.

Questions and Discussion
  • Parameter Ordering and Count in range():

    • Question: How many parameters can range() accept, what is their order, and which bounds are inclusive?

    • Answer: The function accepts up to three integer arguments in the order range(start, end, step). The start bound is inclusive, while the end bound is strictly exclusive. When passing a single argument range(end), start defaults to 00 and step defaults to 11.

  • Harmonic Series Lower Bound:

    • Question: Why does the harmonic series range begin at index 11 rather than index 00?

    • Answer: The harmonic series terms are defined as 1k\frac{1}{k}. Evaluating this term at k=0k = 0 results in 10\frac{1}{0}, which is mathematically undefined and raises a runtime ZeroDivisionError.

  • Classroom Photo Etiquette:

    • Prompt: A student asked to take a photograph of the whiteboard.

    • Response: Students should ask permission before photographing the whiteboard during lecture so the instructor can step aside and remain out of the image.

  • Indentation of the Bit-Tracker Halving:

    • Question: In the binary conversion algorithm, why is v = v // 2 placed outside the if-else block?

    • Answer: Halving the bit tracker must occur on every pass of the while loop regardless of whether a 0 or a 1 was output. Placing it at the outer loop indentation level ensures the tracker shifts downward to the next power of two on every step.

  • Terminal Pathing and Sibling Directories:

    • Prompt: A student could not change directories into IPP using cd IPP from /workspace/control_flow.

    • Response: The active directory path is verified using pwd. Because IPP and control_flow are siblings under /workspace, the command must move up to the parent directory first via cd ../IPP.

  • Functionality of stdrandom.bernoulli():

    • Question: Where does stdrandom.bernoulli() originate and what does it return by default?

    • Answer: It comes from the stdrandom library and models a Bernoulli trial with binary boolean outcomes (True or False). By default, it uses a success probability of 0.50.5, simulating a fair 50%50\% coin toss. Passing a float argument between 0.00.0 and 1.01.0 adjusts the probability of returning True.

  • Inline Conditional Assignment Syntax for Wins:

    • Question: In the statement wins += 1 if cash == goal else 0, does else 0 set cash or accumulated wins to zero?

    • Answer: No. The ternary expression 1 if cash == goal else 0 evaluates to 11 if cash == goal is true, and evaluates to 00 if it is false. The += operator then adds that evaluated result to wins (+1+1 for a win, or +0+0 for a loss). It never modifies cash nor does it reset accumulated wins to zero.