CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mpmath

Python library for arbitrary-precision floating-point arithmetic

Pending
Overview
Eval results
Files

pattern-recognition.mddocs/

Pattern Recognition and Mathematical Identification

Tools for identifying mathematical constants, finding integer relations, polynomial fitting, and discovering mathematical patterns in numerical data.

Capabilities

Integer Relation Detection

Find integer linear combinations that sum to zero or small values.

def pslq(x, tol=None, maxcoeff=1000, maxsteps=100, verbose=False):
    """
    PSLQ algorithm for finding integer relations.
    
    Args:
        x: List of real numbers to find relations among
        tol: Tolerance for relation detection (default: machine precision)
        maxcoeff: Maximum coefficient size to search (default: 1000)
        maxsteps: Maximum algorithm steps (default: 100)
        verbose: Print algorithm progress (default: False)
        
    Returns:
        List of integers [a₁, a₂, ..., aₙ] such that a₁x₁ + a₂x₂ + ... + aₙxₙ ≈ 0
        Returns None if no relation found within constraints
    """

Mathematical Constant Identification

Identify unknown constants by matching against known mathematical constants.

def identify(x, constants=None, tol=None, maxcoeff=1000, verbose=False, full=False):
    """
    Identify mathematical constant by finding simple expressions.
    
    Args:
        x: Number to identify
        constants: List of known constants to use in identification
                  (default: π, e, γ, φ, ln(2), etc.)
        tol: Tolerance for matching (default: machine precision)
        maxcoeff: Maximum coefficient in expressions (default: 1000)
        verbose: Print search details (default: False)
        full: Return all found relations (default: False, returns best match)
        
    Returns:
        String description of identified constant or None if not found
        If full=True, returns list of all plausible expressions
    """

Polynomial Root Finding and Fitting

Find polynomials with given roots or fit polynomials to data.

def findpoly(roots, tol=None, maxdegree=None, **kwargs):
    """
    Find polynomial with given roots.
    
    Args:
        roots: List of polynomial roots (real or complex)
        tol: Tolerance for coefficient simplification
        maxdegree: Maximum polynomial degree (default: len(roots))
        **kwargs: Additional options
        
    Returns:
        List of polynomial coefficients [aₙ, aₙ₋₁, ..., a₁, a₀]
        representing aₙxⁿ + aₙ₋₁xⁿ⁻¹ + ... + a₁x + a₀
    """

Usage Examples

import mpmath
from mpmath import mp

# Set precision for better identification
mp.dps = 50

# Example 1: Integer relation detection with PSLQ
print("=== Integer Relations with PSLQ ===")

# Find relation for π, e, and some combination
x = [mp.pi, mp.e, mp.pi - mp.e]
relation = mp.pslq(x, maxcoeff=100)
if relation:
    print(f"Found relation: {relation}")
    # Verify the relation
    result = sum(relation[i] * x[i] for i in range(len(x)))
    print(f"Verification: {result}")
else:
    print("No integer relation found")

# Example 2: Famous mathematical relations
# Euler's identity: e^(iπ) + 1 = 0, so [1, 1] should be a relation for [e^(iπ), 1]
vals = [mp.exp(mp.j * mp.pi), 1]
relation = mp.pslq([mp.re(vals[0]), mp.im(vals[0]), vals[1]])
print(f"Euler identity relation: {relation}")

# Example 3: Identify mathematical constants
print("\n=== Constant Identification ===")

# Identify well-known constants
constants_to_test = [
    mp.pi,
    mp.e,
    mp.sqrt(2),
    mp.pi**2 / 6,  # ζ(2)
    mp.euler,      # Euler-Mascheroni constant
    mp.phi,        # Golden ratio
    (1 + mp.sqrt(5)) / 2,  # Another form of golden ratio
]

for const in constants_to_test:
    identification = mp.identify(const)
    print(f"{const} → {identification}")

# Example 4: Identify unknown expressions
print("\n=== Identifying Unknown Expressions ===")

# Create some "unknown" values and try to identify them
unknown1 = mp.pi**2 / 8
identification1 = mp.identify(unknown1)
print(f"{unknown1} → {identification1}")

unknown2 = mp.sqrt(mp.pi) * mp.gamma(0.5)
identification2 = mp.identify(unknown2)
print(f"{unknown2} → {identification2}")

unknown3 = mp.ln(2) + mp.ln(3) - mp.ln(6)  # Should be 0
identification3 = mp.identify(unknown3)
print(f"{unknown3} → {identification3}")

# Example 5: Polynomial with known roots
print("\n=== Polynomial Fitting ===")

# Find polynomial with roots 1, 2, 3
roots = [1, 2, 3]
poly_coeffs = mp.findpoly(roots)
print(f"Polynomial with roots {roots}:")
print(f"Coefficients: {poly_coeffs}")

# Verify by evaluating polynomial at roots
def eval_poly(coeffs, x):
    return sum(coeffs[i] * x**(len(coeffs)-1-i) for i in range(len(coeffs)))

for root in roots:
    value = eval_poly(poly_coeffs, root)
    print(f"P({root}) = {value}")

# Example 6: Complex roots
print("\n=== Complex Polynomial Roots ===")
complex_roots = [1+1j, 1-1j, 2]  # Complex conjugate pair + real root
complex_poly = mp.findpoly(complex_roots)
print(f"Polynomial with complex roots {complex_roots}:")
print(f"Coefficients: {complex_poly}")

# Example 7: Advanced PSLQ applications
print("\n=== Advanced PSLQ Applications ===")

# Test for algebraic relations involving special functions
# Example: Is there a relation between π, ln(2), and ζ(3)?
test_values = [mp.pi, mp.ln(2), mp.zeta(3)]
relation = mp.pslq(test_values, maxcoeff=20)
if relation:
    print(f"Found relation among π, ln(2), ζ(3): {relation}")
    verification = sum(relation[i] * test_values[i] for i in range(len(test_values)))
    print(f"Verification: {verification}")
else:
    print("No simple relation found among π, ln(2), ζ(3)")

# Example 8: Identify ratios of constants
print("\n=== Identifying Ratios ===")

ratio1 = mp.pi / 4
identification = mp.identify(ratio1)
print(f"π/4 = {ratio1} → {identification}")

ratio2 = mp.e / mp.pi
identification = mp.identify(ratio2)
print(f"e/π = {ratio2} → {identification}")

# Example 9: Series and limit identification
print("\n=== Series Identification ===")

# Compute a series value and try to identify it
def harmonic_series_partial(n):
    return sum(mp.mpf(1)/k for k in range(1, n+1))

h_100 = harmonic_series_partial(100)
h_100_minus_ln = h_100 - mp.ln(100)
identification = mp.identify(h_100_minus_ln)
print(f"H₁₀₀ - ln(100) = {h_100_minus_ln}")
print(f"Identification: {identification}")

# Example 10: Numerical integration results
print("\n=== Integration Result Identification ===")

# Integrate e^(-x²) from 0 to ∞ and identify result
def gaussian_integral():
    return mp.quad(lambda x: mp.exp(-x**2), [0, mp.inf])

integral_result = gaussian_integral()
identification = mp.identify(integral_result)
print(f"∫₀^∞ e^(-x²) dx = {integral_result}")
print(f"Identification: {identification}")
print(f"√π/2 = {mp.sqrt(mp.pi)/2}")  # Known exact value

# Example 11: Working with algebraic numbers
print("\n=== Algebraic Number Relations ===")

# Find minimal polynomial for √2 + √3
sqrt2_plus_sqrt3 = mp.sqrt(2) + mp.sqrt(3)
# To find minimal polynomial, we can use powers
powers = [sqrt2_plus_sqrt3**i for i in range(5)]  # Include x⁰, x¹, x², x³, x⁴
relation = mp.pslq(powers, maxcoeff=100)
if relation:
    print(f"Minimal polynomial relation for √2 + √3: {relation}")
    # This should give us the minimal polynomial coefficients

print("\n=== Pattern Recognition Complete ===")

Advanced Features

PSLQ Algorithm Details

  • Based on the Bailey-Borwein-Plouffe algorithm
  • Finds integer relations with high confidence
  • Adjustable precision and coefficient bounds
  • Handles both real and complex numbers

Constant Database

The identification system includes knowledge of:

  • Elementary constants: π, e, √2, ln(2), etc.
  • Special function values: ζ(2), ζ(3), Γ(1/3), etc.
  • Algebraic numbers: Golden ratio, cube roots of unity
  • Combinatorial constants: Catalan's constant, Euler-Mascheroni constant

Polynomial Analysis

  • Finds exact rational coefficients when possible
  • Handles complex roots and conjugate pairs
  • Supports various coefficient formats
  • Can work with approximate roots

Applications

Mathematical Research

  • Conjecture verification: Test suspected mathematical relations
  • Constant evaluation: Identify values from numerical computation
  • Pattern discovery: Find unexpected connections between constants

Computational Mathematics

  • Result verification: Confirm analytical predictions
  • Error analysis: Detect computational mistakes
  • Symbolic computation: Bridge numerical and symbolic methods

Educational Applications

  • Concept illustration: Demonstrate mathematical relationships
  • Problem solving: Identify unknown quantities in exercises
  • Mathematical exploration: Discover patterns in student investigations

These tools provide powerful capabilities for mathematical discovery and verification, enabling researchers to find hidden patterns and confirm theoretical predictions through high-precision numerical computation.

Install with Tessl CLI

npx tessl i tessl/pypi-mpmath

docs

core-arithmetic.md

elementary-functions.md

elliptic-modular-functions.md

index.md

linear-algebra.md

mathematical-constants.md

numerical-calculus.md

pattern-recognition.md

signal-processing.md

special-functions.md

visualization.md

tile.json