Skip to main content

A high-precision Python library for arbitrary precision floating-point arithmetic with growable exponents and fractions

Project description

FlexFloat

Python 3.11+ License: MIT PyPI version

A high-precision Python library for arbitrary precision floating-point arithmetic with growable exponents and growable fractions. FlexFloat extends IEEE 754 double-precision format to handle numbers beyond the standard range while increasing fraction precision as exponent ranges expand.

โœจ Key Features

  • ๐Ÿ”ข Growable Exponents: Dynamically expand exponent size to handle extremely large (>10^308) or small (<10^-308) numbers
  • ๐ŸŽฏ Growable Fractions: Increase fraction precision proportionally as exponent ranges expand
  • โšก Full Arithmetic Support: Addition, subtraction, multiplication, division, and power operations
  • ๐Ÿ“ Complete Math Library: Comprehensive mathematical functions including trigonometric, logarithmic, exponential, and hyperbolic functions
  • ๐Ÿ”ง Multiple BitArray Backends: Choose between bool-list, int64-list, and big-integer implementations for optimal performance
  • ๐ŸŒŸ Special Value Handling: Complete support for NaN, ยฑinfinity, and zero values
  • ๐Ÿ›ก๏ธ Overflow Protection: Automatic exponent and fraction growth prevents overflow/underflow errors
  • ๐Ÿ“Š IEEE 754 Baseline: Compatible with standard double-precision values before growth is needed

๐Ÿš€ Quick Start

Installation

pip install flexfloat

Basic Usage

from flexfloat import FlexFloat

# Create FlexFloat instances
a = FlexFloat.from_float(1.5)
b = FlexFloat.from_float(2.5)

# Perform arithmetic operations
result = a + b
print(result.to_float())  # 4.0

# Handle very large numbers that would overflow standard floats
large_a = FlexFloat.from_float(1e308)
large_b = FlexFloat.from_float(1e308)
large_result = large_a + large_b

# Result automatically grows exponent and fraction precision to handle overflow
print(f"Exponent grew: {len(large_result.exponent) > len(large_a.exponent)}")
print(f"Fraction grew: {len(large_result.fraction) > len(large_a.fraction)}")
print(f"Can represent: {large_result}")  # No overflow!

Advanced Mathematical Functions

from flexfloat import FlexFloat
from flexfloat.math import sin, cos, log, exp, sqrt, sinh, cosh

# Create FlexFloat instances
x = FlexFloat.from_float(2.0)
y = FlexFloat.from_float(3.0)

# Trigonometric functions
angle = FlexFloat.from_float(1.5708)  # ฯ€/2 radians
sin_result = sin(angle)
cos_result = cos(angle)
print(f"sin(ฯ€/2) = {sin_result.to_float()}")  # โ‰ˆ 1.0
print(f"cos(ฯ€/2) = {cos_result.to_float()}")  # โ‰ˆ 0.0

# Logarithmic and exponential functions
log_result = log(x)  # Natural logarithm
exp_result = exp(x)  # e^x
sqrt_result = sqrt(x)  # โˆšx
print(f"ln(2) = {log_result.to_float()}")
print(f"e^2 = {exp_result.to_float()}")
print(f"โˆš2 = {sqrt_result.to_float()}")

# Hyperbolic functions
sinh_result = sinh(x)
cosh_result = cosh(x)
print(f"sinh(2) = {sinh_result.to_float()}")
print(f"cosh(2) = {cosh_result.to_float()}")

# Power operations with extreme precision
power_result = x ** y  # 2^3 = 8
print(f"2^3 = {power_result.to_float()}")

# Working with mathematical constants
from flexfloat.math import pi, e
circle_area = pi * (x ** FlexFloat.from_float(2.0))  # ฯ€ * rยฒ
print(f"Area of circle with radius 2: {circle_area.to_float()}")

๐Ÿ”ง BitArray Backends

FlexFloat supports multiple BitArray implementations for different performance characteristics. You can use them directly or configure FlexFloat to use a specific implementation:

from flexfloat import (
    FlexFloat, 
    ListBoolBitArray,
    ListInt64BitArray,
    BigIntBitArray
)

# Configure FlexFloat to use a specific BitArray implementation
FlexFloat.set_bitarray_implementation(ListBoolBitArray)  # Default
flex_bool = FlexFloat.from_float(42.0)

FlexFloat.set_bitarray_implementation(ListInt64BitArray)  # For performance
flex_int64 = FlexFloat.from_float(42.0)

FlexFloat.set_bitarray_implementation(BigIntBitArray)  # For very large arrays
flex_bigint = FlexFloat.from_float(42.0)

# Use BitArray implementations directly
bits = [True, False, True, False]
bool_array = ListBoolBitArray.from_bits(bits)
int64_array = ListInt64BitArray.from_bits(bits)
bigint_array = BigIntBitArray.from_bits(bits)

Implementation Comparison

Implementation Best For Pros Cons
ListBoolBitArray Testing and development Simple, flexible, easy to debug Slower for large operations
ListInt64BitArray Standard operations Fast for medium-sized arrays, memory efficient Some overhead for very small arrays
BigIntBitArray Any usescases Python already optimizes it Overhead for small arrays

๐Ÿ“š API Reference

Core Operations

# Construction
FlexFloat.from_float(value: float) -> FlexFloat
FlexFloat.from_int(value: int) -> FlexFloat
FlexFloat(sign: bool, exponent: BitArray, fraction: BitArray)

# Conversion
flexfloat.to_float() -> float
flexfloat.to_int() -> int

# Arithmetic Operations
a + b, a - b, a * b, a / b, a ** b
abs(a), -a

# Comparison Operations  
a == b, a != b, a < b, a <= b, a > b, a >= b

Mathematical Functions

FlexFloat provides a comprehensive math library similar to Python's math module:

from flexfloat.math import *

# Exponential and Power Functions
exp(x)      # e^x
expm1(x)    # exp(x) - 1 (accurate for small x)
pow(x, y)   # x^y

# Logarithmic Functions
log(x)       # Natural logarithm (base e)
log10(x)     # Base-10 logarithm
log2(x)      # Base-2 logarithm
log1p(x)     # log(1 + x) (accurate for small x)

# Trigonometric Functions
sin(x), cos(x), tan(x)           # Basic trig functions
asin(x), acos(x), atan(x)        # Inverse trig functions
atan2(y, x)                      # Two-argument arctangent
degrees(x), radians(x)           # Angle conversion

# Hyperbolic Functions
sinh(x), cosh(x), tanh(x)        # Hyperbolic functions
asinh(x), acosh(x), atanh(x)     # Inverse hyperbolic functions

# Square Root Functions
sqrt(x)      # Square root
cbrt(x)      # Cube root

# Mathematical Constants
pi, e, tau   # ฯ€, Euler's number, ฯ„ (2ฯ€)
inf, nan     # Positive infinity, Not a Number

# Utility Functions
ceil(x), floor(x)                # Ceiling and floor
fmod(x, y)                       # Floating-point remainder
fabs(x)                          # Absolute value
copysign(x, y)                   # Copy sign from y to x

BitArray Configuration

from flexfloat import FlexFloat
from flexfloat.math import sin, cos, pi

# Configure FlexFloat to use a specific BitArray implementation
FlexFloat.set_bitarray_implementation(implementation: Type[BitArray])

Special Values

from flexfloat import FlexFloat

# Create special values
nan_val = FlexFloat.nan()
inf_val = FlexFloat.infinity()
neg_inf = FlexFloat.negative_infinity()  
zero_val = FlexFloat.zero()

# Check for special values
if result.is_nan():
    print("Result is Not a Number")
if result.is_infinite():
    print("Result is infinite")
if result.is_zero():
    print("Result is zero")

๐Ÿงช Development & Testing

Development Installation

git clone https://github.com/ferranSanchezLlado/flexfloat-py.git
cd flexfloat-py
pip install -e ".[dev]"

Running Tests

# Run all tests
python -m pytest tests/

# Run with coverage
python -m pytest tests/ --cov=flexfloat --cov-report=html

# Run specific test categories
python -m pytest tests/test_arithmetic.py  # Arithmetic operations
python -m pytest tests/test_conversions.py  # Number conversions
python -m pytest tests/test_bitarray.py  # BitArray implementations

Code Quality

# Format code
black flexfloat/ tests/

# Sort imports
isort flexfloat/ tests/

# Type checking
mypy flexfloat/

# Linting
pylint flexfloat/
flake8 flexfloat/

๐ŸŽฏ Use Cases

Scientific Computing

from flexfloat import FlexFloat
from flexfloat.math import sin, cos, pi, exp, log

# High-precision trigonometric calculations
def calculate_wave_interference(amplitude, frequency, time):
    ff_amp = FlexFloat.from_float(amplitude)
    ff_freq = FlexFloat.from_float(frequency)
    ff_time = FlexFloat.from_float(time)
    
    wave = ff_amp * sin(ff_freq * ff_time * pi)
    return wave

# Handle calculations that would overflow standard floats
def flex_factorial(n):
    result = FlexFloat.from_float(1.0)
    for i in range(1, n + 1):
        result = result * FlexFloat.from_float(i)
    return result

large_factorial = flex_factorial(1000)  # No overflow!

Financial Calculations

from flexfloat import FlexFloat
from flexfloat.math import log, exp

# High-precision compound interest calculations
def compound_interest(principal, rate, years, compounds_per_year):
    p = FlexFloat.from_float(principal)
    r = FlexFloat.from_float(rate)
    n = FlexFloat.from_float(compounds_per_year)
    t = FlexFloat.from_float(years)
    
    # A = P(1 + r/n)^(nt)
    rate_per_period = r / n
    exponent = n * t
    base = FlexFloat.from_float(1.0) + rate_per_period
    
    final_amount = p * (base ** exponent)
    return final_amount

# Calculate compound interest over very long periods with high precision
result = compound_interest(1000000.0, 0.05, 100, 12)

Physics Simulations

from flexfloat import FlexFloat
from flexfloat.math import sqrt, pi, exp

# Handle extreme values in physics calculations
c = FlexFloat.from_float(299792458)  # Speed of light (m/s)
mass = FlexFloat.from_float(1e-30)   # Atomic mass (kg)

# E = mcยฒ with extreme precision
energy = mass * c * c

# Quantum mechanics - wave function calculations
def gaussian_wave_packet(x, x0, sigma, k0):
    ff_x = FlexFloat.from_float(x)
    ff_x0 = FlexFloat.from_float(x0)
    ff_sigma = FlexFloat.from_float(sigma)
    ff_k0 = FlexFloat.from_float(k0)
    
    # ฯˆ(x) = exp(-(x-x0)ยฒ/(4ฯƒยฒ)) * exp(ik0x)
    displacement = ff_x - ff_x0
    gaussian = exp(-(displacement * displacement) / (FlexFloat.from_float(4.0) * ff_sigma * ff_sigma))
    phase = ff_k0 * ff_x
    
    return gaussian  # Real part only for this example

๐Ÿ—๏ธ Architecture

FlexFloat is built with a modular architecture:

flexfloat/
โ”œโ”€โ”€ core.py              # Main FlexFloat class and arithmetic operations
โ”œโ”€โ”€ types.py             # Type definitions and protocols
โ”œโ”€โ”€ math/                # Complete mathematical function library
โ”‚   โ”œโ”€โ”€ __init__.py          # Math module exports
โ”‚   โ”œโ”€โ”€ constants.py         # Mathematical constants (ฯ€, e, etc.)
โ”‚   โ”œโ”€โ”€ exponential.py       # exp, expm1, pow functions
โ”‚   โ”œโ”€โ”€ logarithmic.py       # log, log10, log2, log1p functions
โ”‚   โ”œโ”€โ”€ trigonometric.py     # sin, cos, tan and inverse functions
โ”‚   โ”œโ”€โ”€ hyperbolic.py        # sinh, cosh, tanh and inverse functions
โ”‚   โ”œโ”€โ”€ sqrt.py              # sqrt, cbrt functions
โ”‚   โ”œโ”€โ”€ floating_point.py    # IEEE 754 utilities
โ”‚   โ””โ”€โ”€ utility.py           # ceil, floor, fmod and other utilities
โ”œโ”€โ”€ bitarray/            # BitArray implementations
โ”‚   โ”œโ”€โ”€ bitarray.py          # Abstract base class
โ”‚   โ”œโ”€โ”€ bitarray_bool.py     # List[bool] implementation
โ”‚   โ”œโ”€โ”€ bitarray_int64.py    # List[int64] implementation  
โ”‚   โ”œโ”€โ”€ bitarray_bigint.py   # Python int implementation
โ”‚   โ””โ”€โ”€ bitarray_mixins.py   # Common functionality
โ””โ”€โ”€ __init__.py          # Public API exports

Design Principles

  1. IEEE 754 Compatibility: Start with standard double-precision format
  2. Graceful Scaling: Automatically expand exponent and fraction together when needed
  3. Precision Preservation: Grow fraction capacity proportionally instead of keeping it fixed
  4. Performance Options: Multiple backends for different use cases
  5. Pythonic Interface: Natural syntax for mathematical operations
  6. Comprehensive Math Library: Complete set of mathematical functions matching Python's math module
  7. Special Value Handling: Proper IEEE 754 semantics for NaN, infinity, and zero

๐Ÿ“Š Performance Considerations

When to Use FlexFloat

โœ… Good for:

  • Calculations requiring numbers > 10^308 or < 10^-308
  • Scientific computing with extreme values
  • Financial calculations requiring high precision
  • Preventing overflow/underflow in long calculations

โŒ Consider alternatives for:

  • Simple arithmetic with standard-range numbers
  • Performance-critical tight loops
  • Applications where standard float precision is sufficient

Optimization Tips

from flexfloat import FlexFloat, ListInt64BitArray, BigIntBitArray
from flexfloat.math import sin, cos, pi

# Choose the right BitArray implementation for your use case
# For standard operations with moderate precision
FlexFloat.set_bitarray_implementation(ListInt64BitArray)

# For most use cases, Python's int is already optimized
FlexFloat.set_bitarray_implementation(BigIntBitArray)

# Use mathematical constants from the math module
from flexfloat.math import pi, e
circle_area = pi * radius * radius  # More accurate than FlexFloat.from_float(3.14159...)

# Batch operations when possible
values = [FlexFloat.from_float(x) for x in range(1000)]
sum_result = sum(values, FlexFloat.zero())

# Use appropriate precision for your use case
if value_in_standard_range:
    result = float(flexfloat_result.to_float())  # Convert back if needed

๐Ÿ“‹ Roadmap

โœ… Version 1.0.0 - Complete Core Features

  • Initial release with basic arithmetic and special values
  • Complete mathematical function library (trigonometric, logarithmic, exponential, hyperbolic)
  • Square root and power functions
  • Mathematical constants (ฯ€, e, ฯ„)
  • Comprehensive test suite with high coverage
  • Multiple BitArray backend implementations
  • IEEE 754 compatibility and special value handling

๐Ÿšง Future Enhancements

  • Performance optimizations for large arrays
  • Serialization support (JSON, pickle)
  • Decimal mode for exact decimal representation
  • Complex number support (FlexComplex class)
  • Additional utility functions (gamma, erf, etc.)
  • GPU acceleration support
  • Integration with NumPy arrays

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • IEEE 754 standard for floating-point arithmetic foundation
  • Python community for inspiration and best practices
  • Contributors and users who help improve the library

๐Ÿ“ž Support

  • ๐Ÿ“š Documentation: Full API documentation available in docstrings
  • ๐Ÿ› Issues: Report bugs on GitHub Issues
  • ๐Ÿ’ฌ Discussions: Join conversations on GitHub Discussions
  • ๐Ÿ“ง Contact: Reach out to the maintainer for questions

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flexfloat-1.1.3.tar.gz (207.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flexfloat-1.1.3-py3-none-any.whl (55.0 kB view details)

Uploaded Python 3

File details

Details for the file flexfloat-1.1.3.tar.gz.

File metadata

  • Download URL: flexfloat-1.1.3.tar.gz
  • Upload date:
  • Size: 207.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for flexfloat-1.1.3.tar.gz
Algorithm Hash digest
SHA256 117f0ff869df412f3182a2a30ed0bea9c9031f5cf4142e428d419b0c4b97c8bf
MD5 fb149325a6ccb3b29367055c445d58d7
BLAKE2b-256 e7681ca7756756095e210640406e5fae18150cbf120d004a6b4d0486003f87ce

See more details on using hashes here.

Provenance

The following attestation bundles were made for flexfloat-1.1.3.tar.gz:

Publisher: release.yml on ferranSanchezLlado/flexfloat-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file flexfloat-1.1.3-py3-none-any.whl.

File metadata

  • Download URL: flexfloat-1.1.3-py3-none-any.whl
  • Upload date:
  • Size: 55.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for flexfloat-1.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 19f80dc8e18112a8421e7fee2787b3cad0728d0fdcf944ef888c96ace1a64906
MD5 489d0a9c5afa82744460f686e35a8a20
BLAKE2b-256 182e9665e1ccdbf8619d2ddd0a3b2da4549a3231845ac18754b6b2a41245446c

See more details on using hashes here.

Provenance

The following attestation bundles were made for flexfloat-1.1.3-py3-none-any.whl:

Publisher: release.yml on ferranSanchezLlado/flexfloat-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page