A high-precision Python library for arbitrary precision floating-point arithmetic with growable exponents and fixed-size fractions
Project description
FlexFloat 1.0.0
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
- ๐ 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 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 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
- 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
- Comprehensive Math Library: Complete set of mathematical functions matching Python's math module
- 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
floatprecision 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
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-1.0.0.tar.gz.
File metadata
- Download URL: flexfloat-1.0.0.tar.gz
- Upload date:
- Size: 111.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3da69f4aa6ebac158f76ea422557fcf2f690f4e7577001d0d70a6ec07b187854
|
|
| MD5 |
19ac49284d85fa93db37a87bbb79c170
|
|
| BLAKE2b-256 |
cbefad2ec3c1b74a7f2ef602cfb94c14a31c28ed1edb0be2e9ac4a01bfbaad6d
|
Provenance
The following attestation bundles were made for flexfloat-1.0.0.tar.gz:
Publisher:
manual-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-1.0.0.tar.gz -
Subject digest:
3da69f4aa6ebac158f76ea422557fcf2f690f4e7577001d0d70a6ec07b187854 - Sigstore transparency entry: 346313493
- Sigstore integration time:
-
Permalink:
ferranSanchezLlado/flexfloat-py@0fa73707297719509fbc3cecf65b1a3b18d1be30 -
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:
manual-release.yml@0fa73707297719509fbc3cecf65b1a3b18d1be30 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file flexfloat-1.0.0-py3-none-any.whl.
File metadata
- Download URL: flexfloat-1.0.0-py3-none-any.whl
- Upload date:
- Size: 54.8 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 |
2424f444b4a5a71a77c1b779c20a3639a3e27f8fe3a805883e4438285b69c3e1
|
|
| MD5 |
7ee0ed3b9ffe05748de7bdf160cc8bdb
|
|
| BLAKE2b-256 |
7bc338592dc73843899591e9254301185c3100108fda4233e404fbd83c0173d3
|
Provenance
The following attestation bundles were made for flexfloat-1.0.0-py3-none-any.whl:
Publisher:
manual-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-1.0.0-py3-none-any.whl -
Subject digest:
2424f444b4a5a71a77c1b779c20a3639a3e27f8fe3a805883e4438285b69c3e1 - Sigstore transparency entry: 346313495
- Sigstore integration time:
-
Permalink:
ferranSanchezLlado/flexfloat-py@0fa73707297719509fbc3cecf65b1a3b18d1be30 -
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:
manual-release.yml@0fa73707297719509fbc3cecf65b1a3b18d1be30 -
Trigger Event:
workflow_dispatch
-
Statement type: