-
-
Save rust-play/8cca2d5036c7a2c9394f8f8e6e342cff to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use num_bigint::BigInt; | |
| use num_traits::{One, Zero}; | |
| // ============================================================================ | |
| // EXECUTABLE PROOFS & MATHEMATICAL VERIFICATION MODULE | |
| // ============================================================================ | |
| pub mod proofs { | |
| use std::f64::consts::E; | |
| /// PROOF 1: Computable Irrationals Require Non-Halting Streams | |
| /// | |
| /// Verifies that any finite positional digit representation in base b | |
| /// maps strictly to a rational number p/b^N. | |
| pub fn verify_finite_base_representation_is_rational( | |
| digits: &[u8], | |
| base: u64, | |
| ) -> (u64, u64) { | |
| println!("\n [Proof 1 Execution]"); | |
| println!(" Input digits: {:?}, Base: {}", digits, base); | |
| let mut numerator = 0u64; | |
| let mut denominator = 1u64; | |
| for (idx, &digit) in digits.iter().enumerate() { | |
| let prev_num = numerator; | |
| let prev_den = denominator; | |
| numerator = numerator * base + (digit as u64); | |
| denominator *= base; | |
| println!( | |
| " Step {}: digit={} | p = ({} * {}) + {} = {} | q = {} * {} = {}", | |
| idx + 1, digit, prev_num, base, digit, numerator, prev_den, base, denominator | |
| ); | |
| } | |
| // Reduces via Euclidean algorithm | |
| fn gcd(a: u64, b: u64) -> u64 { | |
| if b == 0 { a } else { gcd(b, a % b) } | |
| } | |
| let g = gcd(numerator, denominator); | |
| let reduced_num = numerator / g; | |
| let reduced_den = denominator / g; | |
| println!( | |
| " Euclidean GCD({}, {}) = {} -> Reduced Fraction: {} / {}", | |
| numerator, denominator, g, reduced_num, reduced_den | |
| ); | |
| (reduced_num, reduced_den) | |
| } | |
| /// PROOF 2: e as the Tetration Convergence Boundary | |
| /// | |
| /// Numerically tests convergence of infinite power tower y_{n+1} = x^{y_n} | |
| /// and verifies the stability bound x \in [e^{-e}, e^{1/e}]. | |
| pub fn verify_tetration_bounds() -> (f64, f64, bool, bool) { | |
| println!("\n [Proof 2 Execution]"); | |
| let lower_bound = (-E).exp(); // e^{-e} \approx 0.065988 | |
| let upper_bound = E.powf(1.0 / E); // e^{1/e} \approx 1.444668 | |
| println!(" Calculated Lower Bound (e^-e): {:.8}", lower_bound); | |
| println!(" Calculated Upper Bound (e^(1/e)): {:.8}", upper_bound); | |
| let simulate_tower = |x: f64, label: &str| -> Option<f64> { | |
| let mut y = 1.0; | |
| println!(" Evaluating power tower for {} (x = {:.6}):", label, x); | |
| for step in 0..10_000 { | |
| let next_y = x.powf(y); | |
| if step < 5 || step % 2000 == 0 || next_y.is_nan() || next_y.is_infinite() { | |
| println!(" Iteration {:5}: y = {:.8}", step, y); | |
| } | |
| y = next_y; | |
| if y.is_nan() || y.is_infinite() { | |
| println!(" [!] Divergence detected at step {}", step); | |
| return None; | |
| } | |
| } | |
| println!(" Final Convergent Limit: {:.8}", y); | |
| Some(y) | |
| }; | |
| // Convergence check at upper edge (should converge to e) | |
| let upper_converges = simulate_tower(upper_bound, "Upper Bound Edge") | |
| .map(|limit| { | |
| let diff = (limit - E).abs(); | |
| println!(" Abs diff from e ({:.8}): {:.8}", E, diff); | |
| diff < 1e-3 | |
| }) | |
| .unwrap_or(false); | |
| // Divergence check outside upper boundary | |
| let over_bound_diverges = simulate_tower(upper_bound + 0.05, "Out of Bounds Target (x + 0.05)").is_none(); | |
| (lower_bound, upper_bound, upper_converges, over_bound_diverges) | |
| } | |
| /// PROOF 3: \pi as Asymptotic Normalizer in Orthogonal Lattices | |
| /// | |
| /// Computes 2D Random Walk Return Probability P_{2n} = (1/4^{2n}) * \binom{2n}{n}^2 | |
| /// and verifies convergence to 1 / (\pi * n). | |
| pub fn verify_2d_lattice_asymptotic_pi(n: usize) -> (f64, f64, f64) { | |
| println!("\n [Proof 3 Execution]"); | |
| println!(" Evaluating 2D Random Walk Return Probability for 2n = {} steps (n = {})", 2 * n, n); | |
| let mut log_p = 0.0f64; | |
| for i in 1..=n { | |
| let term = ((n + i) as f64).ln() - (i as f64).ln() - (4.0f64).ln(); | |
| log_p += term; | |
| if i <= 3 || i == n { | |
| println!(" i = {:3}: log_p accumulator = {:.8}", i, log_p); | |
| } | |
| } | |
| let p_2n = log_p.exp().powi(2); | |
| let asymptotic = 1.0 / (std::f64::consts::PI * n as f64); | |
| let relative_error = (p_2n - asymptotic).abs() / asymptotic; | |
| println!(" Calculated Exact P_2n: {:.8e}", p_2n); | |
| println!(" Theoretical Asymptotic 1/(pi * n): {:.8e}", asymptotic); | |
| println!(" Relative Error: {:.6}%", relative_error * 100.0); | |
| (p_2n, asymptotic, relative_error) | |
| } | |
| /// PROOF 4: Discrete Physical Limits & Quantization Error | |
| /// | |
| /// Models state resolution limits of finite B-bit physical hardware. | |
| pub fn verify_quantization_bound(bits: u32, domain_width: f64) -> (usize, f64, f64) { | |
| println!("\n [Proof 4 Execution]"); | |
| let states = 1usize << bits; | |
| let delta_x = domain_width / (states as f64); | |
| let min_uncertainty = delta_x / 2.0; | |
| println!(" Hardware Width: {} bits", bits); | |
| println!(" Discrete State Count (2^{}): {}", bits, states); | |
| println!(" Domain Spatial Step (dx): {:.8e}", delta_x); | |
| println!(" Minimum Quantization Uncertainty (dx / 2): {:.8e}", min_uncertainty); | |
| (states, delta_x, min_uncertainty) | |
| } | |
| } | |
| // ============================================================================ | |
| // Mathematical Rationale: Spigot Algorithm for e | |
| // ============================================================================ | |
| pub struct ESpigot { | |
| a: Vec<usize>, | |
| step_count: usize, | |
| verbose: bool, | |
| } | |
| impl ESpigot { | |
| pub fn new(capacity: usize) -> Self { | |
| Self { | |
| a: vec![1; capacity], | |
| step_count: 0, | |
| verbose: false, | |
| } | |
| } | |
| pub fn with_verbose(capacity: usize, verbose: bool) -> Self { | |
| Self { | |
| a: vec![1; capacity], | |
| step_count: 0, | |
| verbose, | |
| } | |
| } | |
| } | |
| impl Iterator for ESpigot { | |
| type Item = usize; | |
| fn next(&mut self) -> Option<Self::Item> { | |
| if self.a.is_empty() { | |
| return None; | |
| } | |
| self.step_count += 1; | |
| let mut carry = 0; | |
| if self.verbose { | |
| println!( | |
| " [ESpigot Step {:2}] Prev state sample (head 5): {:?}", | |
| self.step_count, | |
| &self.a[..self.a.len().min(5)] | |
| ); | |
| } | |
| // Process right-to-left across fractional bases: 1/(n+1)!, ..., 1/3!, 1/2! | |
| for i in (0..self.a.len()).rev() { | |
| let base = i + 2; | |
| let temp = self.a[i] * 10 + carry; | |
| carry = temp / base; | |
| self.a[i] = temp % base; | |
| } | |
| if self.verbose { | |
| println!( | |
| " [ESpigot Step {:2}] Emitted digit / carry: {} | New state sample (head 5): {:?}", | |
| self.step_count, | |
| carry, | |
| &self.a[..self.a.len().min(5)] | |
| ); | |
| } | |
| Some(carry) | |
| } | |
| } | |
| // ============================================================================ | |
| // Mathematical Rationale: Stream Spigot Algorithm for \pi (Gibbons / LFT) | |
| // ============================================================================ | |
| pub struct PiSpigot { | |
| q: BigInt, | |
| r: BigInt, | |
| t: BigInt, | |
| k: BigInt, | |
| n: BigInt, | |
| l: BigInt, | |
| step_count: usize, | |
| verbose: bool, | |
| } | |
| impl PiSpigot { | |
| pub fn new() -> Self { | |
| Self { | |
| q: BigInt::one(), | |
| r: BigInt::zero(), | |
| t: BigInt::one(), | |
| k: BigInt::one(), | |
| n: BigInt::from(3), | |
| l: BigInt::from(3), | |
| step_count: 0, | |
| verbose: false, | |
| } | |
| } | |
| pub fn with_verbose(verbose: bool) -> Self { | |
| Self { | |
| q: BigInt::one(), | |
| r: BigInt::zero(), | |
| t: BigInt::one(), | |
| k: BigInt::one(), | |
| n: BigInt::from(3), | |
| l: BigInt::from(3), | |
| step_count: 0, | |
| verbose, | |
| } | |
| } | |
| } | |
| impl Iterator for PiSpigot { | |
| type Item = usize; | |
| fn next(&mut self) -> Option<Self::Item> { | |
| loop { | |
| let four = BigInt::from(4); | |
| if &self.q * &four + &self.r - &self.t < &self.n * &self.t { | |
| self.step_count += 1; | |
| let digit = self.n.to_string().parse::<usize>().unwrap(); | |
| if self.verbose { | |
| println!( | |
| " [PiSpigot Digit {:2}] Output: {} | Matrix State (q:{}, r:{}, t:{}, k:{}, n:{}, l:{})", | |
| self.step_count, digit, self.q, self.r, self.t, self.k, self.n, self.l | |
| ); | |
| } | |
| let hundred = BigInt::from(10); | |
| let nr = (&self.r - &self.n * &self.t) * &hundred; | |
| self.q *= &hundred; | |
| self.n = ((&self.q * &three()) + &nr) / &self.t; | |
| self.r = nr; | |
| return Some(digit); | |
| } else { | |
| let nr = (&self.q * &two() + &self.r) * &self.l; | |
| let nn = (&self.q * &seven() * &self.k + two() + &self.r * &self.l) | |
| / (&self.t * &self.l); | |
| self.q *= &self.k; | |
| self.t *= &self.l; | |
| self.l += two(); | |
| self.k += BigInt::one(); | |
| self.n = nn; | |
| self.r = nr; | |
| if self.verbose && self.step_count < 3 { | |
| println!( | |
| " [PiSpigot Step Transform] Transformed bounds to k={} l={}", | |
| self.k, self.l | |
| ); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| fn two() -> BigInt { BigInt::from(2) } | |
| fn three() -> BigInt { BigInt::from(3) } | |
| fn seven() -> BigInt { BigInt::from(7) } | |
| pub fn main() { | |
| println!("=========================================================================="); | |
| println!("=== EXECUTABLE PROOF VERIFICATIONS (VERBOSE OUTPUT) ==="); | |
| println!("=========================================================================="); | |
| // Proof 1 | |
| let (p, q) = proofs::verify_finite_base_representation_is_rational(&[1, 4, 1, 5, 9], 10); | |
| println!("\n[Proof 1 Result] 5 digits in base 10 reduce to rational p/q: {}/{}", p, q); | |
| // Proof 2 | |
| let (low, high, upper_ok, div_ok) = proofs::verify_tetration_bounds(); | |
| println!( | |
| "\n[Proof 2 Result] Tetration base interval: [{:.5}, {:.5}] | Bound converges to e: {} | Exceeding diverges: {}", | |
| low, high, upper_ok, div_ok | |
| ); | |
| // Proof 3 | |
| let (p_2n, asymptotic, rel_err) = proofs::verify_2d_lattice_asymptotic_pi(100); | |
| println!( | |
| "\n[Proof 3 Result] 2D Return prob P_200 = {:.6e} | 1/(100*pi) = {:.6e} | Rel error: {:.4}%", | |
| p_2n, asymptotic, rel_err * 100.0 | |
| ); | |
| // Proof 4 | |
| let (states, dx, err) = proofs::verify_quantization_bound(16, 1.0); | |
| println!( | |
| "\n[Proof 4 Result] 16-bit hardware states: {} | dx: {:.6e} | Lower precision bound: {:.6e}", | |
| states, dx, err | |
| ); | |
| println!("\n=========================================================================="); | |
| println!("=== SPIGOT DIGIT STREAM OUTPUTS (VERBOSE STEP LOGGING) ==="); | |
| println!("=========================================================================="); | |
| println!("\n--- e Spigot (first 10 digits after decimal, verbose) ---"); | |
| print!("2."); | |
| let e_spigot = ESpigot::with_verbose(40, true); | |
| let e_digits: Vec<usize> = e_spigot.take(10).collect(); | |
| println!("Extracted e digits: {:?}", e_digits); | |
| println!("\n--- Pi Spigot (first 10 digits, verbose) ---"); | |
| let mut pi_spigot = PiSpigot::with_verbose(true); | |
| let first = pi_spigot.next().unwrap(); | |
| print!("{}.", first); | |
| let pi_digits: Vec<usize> = pi_spigot.take(9).collect(); | |
| println!("Extracted Pi digits: {} followed by {:?}", first, pi_digits); | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| #[test] | |
| fn test_e_spigot() { | |
| let digits: Vec<usize> = ESpigot::new(40).take(10).collect(); | |
| assert_eq!(digits, vec![7, 1, 8, 2, 8, 1, 8, 2, 8, 4]); | |
| } | |
| #[test] | |
| fn test_pi_spigot() { | |
| let mut spigot = PiSpigot::new(); | |
| let first = spigot.next().unwrap(); | |
| let rest: Vec<usize> = spigot.take(10).collect(); | |
| assert_eq!(first, 3); | |
| assert_eq!(rest, vec![1, 4, 1, 5, 9, 2, 6, 5, 3, 5]); | |
| } | |
| #[test] | |
| fn test_tetration_proof() { | |
| let (_, high, upper_ok, div_ok) = proofs::verify_tetration_bounds(); | |
| assert!((high - 1.4446678).abs() < 1e-6); | |
| assert!(upper_ok); | |
| assert!(div_ok); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| version = "1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment