A library for arbitrary precision floating point arithmetic
Project description
FlexFloat
A high-precision Python library for arbitrary precision floating-point arithmetic with growable exponents and fixed-size fractions. FlexFloat extends IEEE 754 double-precision format to handle numbers beyond the standard range while maintaining computational efficiency and precision consistency.
✨ Key Features
- 🔢 Growable Exponents: Dynamically expand exponent size to handle extremely large (>10^308) or small (<10^-308) numbers
- 🎯 Fixed-Size Fractions: Maintain IEEE 754-compatible 52-bit fraction precision for consistent accuracy
- ⚡ Full Arithmetic Support: Addition, subtraction, multiplication, division, and power operations
- 🔧 Multiple BitArray Backends: Choose between list-based and int64-based implementations for optimal performance
- 🌟 Special Value Handling: Complete support for NaN, ±infinity, and zero values
- 🛡️ Overflow Protection: Automatic exponent growth prevents overflow/underflow errors
- 📊 IEEE 754 Baseline: Fully compatible with standard double-precision format as the starting point
🚀 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 to handle the overflow
print(f"Exponent bits: {len(large_result.exponent)}") # > 11 (grown beyond IEEE 754)
print(f"Can represent: {large_result}") # No overflow!
Advanced Examples
from flexfloat import FlexFloat
# Mathematical operations
x = FlexFloat.from_float(2.0)
y = FlexFloat.from_float(3.0)
# Power operations
power_result = x ** y # 2^3 = 8
print(power_result.to_float()) # 8.0
# Exponential using Euler's number
e_result = FlexFloat.e ** x # e^2
print(f"e^2 ≈ {e_result.to_float()}")
# Working with extreme values
tiny = FlexFloat.from_float(1e-300)
huge = FlexFloat.from_float(1e300)
extreme_product = tiny * huge
print(f"Product: {extreme_product.to_float()}") # Still computable!
# Precision demonstration
precise_calc = FlexFloat.from_float(1.0) / FlexFloat.from_float(3.0)
print(f"1/3 with 52-bit precision: {precise_calc}")
🔧 BitArray Backends
FlexFloat supports multiple BitArray implementations for different performance characteristics:
from flexfloat import (
FlexFloat,
set_default_implementation,
get_available_implementations
)
# View available implementations
print(get_available_implementations()) # ['list', 'int64']
# Use list-based implementation (default, more flexible)
set_default_implementation('list')
flex_list = FlexFloat.from_float(42.0)
# Use int64-based implementation (faster for small bit arrays)
set_default_implementation('int64')
flex_int64 = FlexFloat.from_float(42.0)
# Both produce the same results with different performance characteristics
Implementation Comparison
| Implementation | Best For | Pros | Cons |
|---|---|---|---|
list[bool] |
Smaller exponents and testing | Flexible, easy to understand | Slower for large numbers |
list[int64] |
Standard operations | Fast for bigger numbers, efficient memory | Overhead for small numbers |
📚 API Reference
Core Operations
# Construction
FlexFloat.from_float(value: float) -> FlexFloat
FlexFloat(sign: bool, exponent: BitArray, fraction: BitArray)
# Conversion
flexfloat.to_float() -> float
# Arithmetic
a + b, a - b, a * b, a / b, a ** b
abs(a), -a
# Mathematical functions
FlexFloat.e ** x # Exponential function
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")
🧪 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
# Handle calculations that would overflow standard floats
from flexfloat import FlexFloat
# Factorial of large numbers
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
# High-precision compound interest calculations
principal = FlexFloat.from_float(1000000.0)
rate = FlexFloat.from_float(1.05) # 5% annual return
years = FlexFloat.from_float(100)
# Calculate compound interest over very long periods
final_amount = principal * (rate ** years)
Physics Simulations
# Handle extreme values in physics calculations
c = FlexFloat.from_float(299792458) # Speed of light
mass = FlexFloat.from_float(1e-30) # Atomic mass
# E = mc² with extreme precision
energy = mass * c * c
🏗️ Architecture
FlexFloat is built with a modular architecture:
flexfloat/
├── core.py # Main FlexFloat class
├── types.py # Type definitions
├── bitarray/ # BitArray implementations
│ ├── bitarray.py # Abstract base class
│ ├── bitarray_list.py # List-based implementation
│ ├── bitarray_int64.py # Int64-based implementation
│ └── bitarray_mixins.py # Common functionality
└── __init__.py # Public API exports
Design Principles
- IEEE 754 Compatibility: Start with standard double-precision format
- Graceful Scaling: Automatically expand exponent when needed
- Precision Preservation: Keep fraction size fixed for consistent accuracy
- Performance Options: Multiple backends for different use cases
- Pythonic Interface: Natural syntax for mathematical operations
📊 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
floatprecision is sufficient
Optimization Tips
# Prefer int64 implementation for standard operations
set_default_implementation('int64')
# 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
- Additional mathematical functions (sin, cos, tan, log, sqrt)
- Serialization support (JSON, pickle)
- Performance optimizations for large arrays
- Complex number support
- Decimal mode for exact decimal representation
📄 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flexfloat-0.1.5.tar.gz.
File metadata
- Download URL: flexfloat-0.1.5.tar.gz
- Upload date:
- Size: 51.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
12a35e42ca95336360c888395ae766dc4f29047096b633013cc142c7a8314366
|
|
| MD5 |
6d6abd66e0344f0e6c50a5fd7542f04c
|
|
| BLAKE2b-256 |
c6a0aecc4e98d4cd00f6c60268cfee7cbfdaca370fbf3bf394b7f63624febca3
|
Provenance
The following attestation bundles were made for flexfloat-0.1.5.tar.gz:
Publisher:
release.yml on ferranSanchezLlado/flexfloat-py
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
flexfloat-0.1.5.tar.gz -
Subject digest:
12a35e42ca95336360c888395ae766dc4f29047096b633013cc142c7a8314366 - Sigstore transparency entry: 315307823
- Sigstore integration time:
-
Permalink:
ferranSanchezLlado/flexfloat-py@a3883282d381c0538c74fe0b3111a75b0c25bfc0 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/ferranSanchezLlado
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@a3883282d381c0538c74fe0b3111a75b0c25bfc0 -
Trigger Event:
pull_request
-
Statement type:
File details
Details for the file flexfloat-0.1.5-py3-none-any.whl.
File metadata
- Download URL: flexfloat-0.1.5-py3-none-any.whl
- Upload date:
- Size: 26.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
00cdfa928dfa2e9b4a91b573d71cd61a861474f7481d22e7f079684924625880
|
|
| MD5 |
a10d34fca18a67e78e88817a688c5fd0
|
|
| BLAKE2b-256 |
d1675deaf014e43f06c250cdeb99496d87f5782b685e93ffba52d9f69cfabeb1
|
Provenance
The following attestation bundles were made for flexfloat-0.1.5-py3-none-any.whl:
Publisher:
release.yml on ferranSanchezLlado/flexfloat-py
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
flexfloat-0.1.5-py3-none-any.whl -
Subject digest:
00cdfa928dfa2e9b4a91b573d71cd61a861474f7481d22e7f079684924625880 - Sigstore transparency entry: 315307846
- Sigstore integration time:
-
Permalink:
ferranSanchezLlado/flexfloat-py@a3883282d381c0538c74fe0b3111a75b0c25bfc0 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/ferranSanchezLlado
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@a3883282d381c0538c74fe0b3111a75b0c25bfc0 -
Trigger Event:
pull_request
-
Statement type: