flexfloat 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: flexfloat
3
+ Version: 0.1.0
4
+ Summary: A library for arbitrary precision floating point arithmetic
5
+ Author: Ferran Sanchez Llado
6
+ License: MIT
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7.0; extra == "dev"
21
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
22
+ Requires-Dist: black>=23.0; extra == "dev"
23
+ Requires-Dist: isort>=5.0; extra == "dev"
24
+ Requires-Dist: mypy>=1.0; extra == "dev"
25
+ Requires-Dist: pylint>=3.0; extra == "dev"
26
+ Requires-Dist: flake8>=6.0; extra == "dev"
27
+
28
+ # FlexFloat
29
+
30
+ A Python library for arbitrary precision floating point arithmetic with a flexible exponent and fixed-size fraction.
31
+
32
+ ## Features
33
+
34
+ - **Growable Exponents**: Handle very large or very small numbers by dynamically adjusting the exponent size
35
+ - **Fixed-Size Fractions**: Maintain precision consistency with IEEE 754-compatible 52-bit fractions
36
+ - **IEEE 754 Compatibility**: Follows IEEE 754 double-precision format as the baseline
37
+ - **Special Value Support**: Handles NaN, positive/negative infinity, and zero values
38
+ - **Arithmetic Operations**: Addition and subtraction with proper overflow/underflow handling
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install flexfloat
44
+ ```
45
+
46
+ ## Development Installation
47
+
48
+ ```bash
49
+ pip install -e ".[dev]"
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ```python
55
+ from flexfloat import FlexFloat
56
+
57
+ # Create FlexFloat instances
58
+ a = FlexFloat.from_float(1.5)
59
+ b = FlexFloat.from_float(2.5)
60
+
61
+ # Perform arithmetic operations
62
+ result = a + b
63
+ print(result.to_float()) # 4.0
64
+
65
+ # Handle very large numbers
66
+ large_a = FlexFloat.from_float(1e308)
67
+ large_b = FlexFloat.from_float(1e308)
68
+ large_result = large_a + large_b
69
+ # Result has grown exponent to handle overflow
70
+ print(len(large_result.exponent)) # > 11 (grows beyond IEEE 754 standard)
71
+ ```
72
+
73
+ ## Running Tests
74
+
75
+ ```bash
76
+ python -m pytest tests
77
+ ```
78
+
79
+
80
+ ## License
81
+
82
+ MIT License
@@ -0,0 +1,55 @@
1
+ # FlexFloat
2
+
3
+ A Python library for arbitrary precision floating point arithmetic with a flexible exponent and fixed-size fraction.
4
+
5
+ ## Features
6
+
7
+ - **Growable Exponents**: Handle very large or very small numbers by dynamically adjusting the exponent size
8
+ - **Fixed-Size Fractions**: Maintain precision consistency with IEEE 754-compatible 52-bit fractions
9
+ - **IEEE 754 Compatibility**: Follows IEEE 754 double-precision format as the baseline
10
+ - **Special Value Support**: Handles NaN, positive/negative infinity, and zero values
11
+ - **Arithmetic Operations**: Addition and subtraction with proper overflow/underflow handling
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install flexfloat
17
+ ```
18
+
19
+ ## Development Installation
20
+
21
+ ```bash
22
+ pip install -e ".[dev]"
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```python
28
+ from flexfloat import FlexFloat
29
+
30
+ # Create FlexFloat instances
31
+ a = FlexFloat.from_float(1.5)
32
+ b = FlexFloat.from_float(2.5)
33
+
34
+ # Perform arithmetic operations
35
+ result = a + b
36
+ print(result.to_float()) # 4.0
37
+
38
+ # Handle very large numbers
39
+ large_a = FlexFloat.from_float(1e308)
40
+ large_b = FlexFloat.from_float(1e308)
41
+ large_result = large_a + large_b
42
+ # Result has grown exponent to handle overflow
43
+ print(len(large_result.exponent)) # > 11 (grows beyond IEEE 754 standard)
44
+ ```
45
+
46
+ ## Running Tests
47
+
48
+ ```bash
49
+ python -m pytest tests
50
+ ```
51
+
52
+
53
+ ## License
54
+
55
+ MIT License
@@ -0,0 +1,13 @@
1
+ """FlexFloat - A library for arbitrary precision floating point arithmetic.
2
+
3
+ This package provides the FlexFloat class for handling floating-point numbers
4
+ with growable exponents and fixed-size fractions.
5
+ """
6
+
7
+ from .bitarray import BitArray
8
+ from .core import FlexFloat
9
+
10
+ __version__ = "0.1.0"
11
+ __author__ = "Ferran Sanchez Llado"
12
+
13
+ __all__ = ["FlexFloat", "BitArray"]
@@ -0,0 +1,253 @@
1
+ """BitArray implementation for the flexfloat package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import struct
6
+ from typing import Iterator, overload
7
+
8
+
9
+ class BitArray:
10
+ """A bit array class that encapsulates a list of booleans with utility methods.
11
+
12
+ This class provides all the functionality previously available through utility functions,
13
+ now encapsulated as methods for better object-oriented design.
14
+ """
15
+
16
+ def __init__(self, bits: list[bool] | None = None):
17
+ """Initialize a BitArray.
18
+
19
+ Args:
20
+ bits: Initial list of boolean values. Defaults to empty list.
21
+ """
22
+ self._bits = bits if bits is not None else []
23
+
24
+ @classmethod
25
+ def from_float(cls, value: float) -> BitArray:
26
+ """Convert a floating-point number to a bit array.
27
+
28
+ Args:
29
+ value (float): The floating-point number to convert.
30
+ Returns:
31
+ BitArray: A BitArray representing the bits of the floating-point number.
32
+ """
33
+ # Pack as double precision (64 bits)
34
+ packed = struct.pack("!d", value)
35
+ # Convert to boolean list
36
+ bits = [bool((byte >> bit) & 1) for byte in packed for bit in range(7, -1, -1)]
37
+ return cls(bits)
38
+
39
+ @classmethod
40
+ def from_signed_int(cls, value: int, length: int) -> BitArray:
41
+ """Convert a signed integer to a bit array using off-set binary representation.
42
+
43
+ Args:
44
+ value (int): The signed integer to convert.
45
+ length (int): The length of the resulting bit array.
46
+ Returns:
47
+ BitArray: A BitArray representing the bits of the signed integer.
48
+ Raises:
49
+ AssertionError: If the value is out of range for the specified length.
50
+ """
51
+ half = 1 << (length - 1)
52
+ max_value = half - 1
53
+ min_value = -half
54
+
55
+ assert (
56
+ min_value <= value <= max_value
57
+ ), "Value out of range for specified length."
58
+
59
+ # Convert to unsigned integer representation
60
+ unsigned_value = value - half
61
+
62
+ bits = [(unsigned_value >> i) & 1 == 1 for i in range(length - 1, -1, -1)]
63
+ return cls(bits)
64
+
65
+ @classmethod
66
+ def zeros(cls, length: int) -> BitArray:
67
+ """Create a BitArray filled with zeros.
68
+
69
+ Args:
70
+ length: The length of the bit array.
71
+ Returns:
72
+ BitArray: A BitArray filled with False values.
73
+ """
74
+ return cls([False] * length)
75
+
76
+ @classmethod
77
+ def ones(cls, length: int) -> BitArray:
78
+ """Create a BitArray filled with ones.
79
+
80
+ Args:
81
+ length: The length of the bit array.
82
+ Returns:
83
+ BitArray: A BitArray filled with True values.
84
+ """
85
+ return cls([True] * length)
86
+
87
+ @staticmethod
88
+ def parse_bitarray(bitstring: str) -> BitArray:
89
+ """Parse a string of bits (with optional spaces) into a BitArray instance."""
90
+ bits = [c == "1" for c in bitstring if c in "01"]
91
+ return BitArray(bits)
92
+
93
+ def to_float(self) -> float:
94
+ """Convert a 64-bit array to a floating-point number.
95
+
96
+ Returns:
97
+ float: The floating-point number represented by the bit array.
98
+ Raises:
99
+ AssertionError: If the bit array is not 64 bits long.
100
+ """
101
+ assert len(self._bits) == 64, "Bit array must be 64 bits long."
102
+
103
+ byte_values = bytearray()
104
+ for i in range(0, 64, 8):
105
+ byte = 0
106
+ for j in range(8):
107
+ if self._bits[i + j]:
108
+ byte |= 1 << (7 - j)
109
+ byte_values.append(byte)
110
+ # Unpack as double precision (64 bits)
111
+ return struct.unpack("!d", bytes(byte_values))[0] # type: ignore
112
+
113
+ def to_int(self) -> int:
114
+ """Convert the bit array to an unsigned integer.
115
+
116
+ Returns:
117
+ int: The integer represented by the bit array.
118
+ """
119
+ return sum((1 << i) for i, bit in enumerate(reversed(self._bits)) if bit)
120
+
121
+ def to_signed_int(self) -> int:
122
+ """Convert a bit array into a signed integer using off-set binary representation.
123
+
124
+ Returns:
125
+ int: The signed integer represented by the bit array.
126
+ Raises:
127
+ AssertionError: If the bit array is empty.
128
+ """
129
+ assert len(self._bits) > 0, "Bit array must not be empty."
130
+
131
+ int_value = self.to_int()
132
+ # Half of the maximum value
133
+ bias = 1 << (len(self._bits) - 1)
134
+ # If the sign bit is set, subtract the bias
135
+ return int_value - bias
136
+
137
+ def shift(self, shift_amount: int, fill: bool = False) -> BitArray:
138
+ """Shift the bit array left or right by a specified number of bits.
139
+
140
+ This function shifts the bits in the array, filling in new bits with the specified fill value.
141
+ If the shift is positive, it shifts left and fills with the fill value at the end.
142
+ If the shift is negative, it shifts right and fills with the fill value at the start.
143
+
144
+ Args:
145
+ shift_amount (int): The number of bits to shift. Positive for left shift, negative for right shift.
146
+ fill (bool): The value to fill in the new bits created by the shift. Defaults to False.
147
+ Returns:
148
+ BitArray: A new BitArray with the bits shifted and filled.
149
+ """
150
+ if shift_amount == 0:
151
+ return self.copy()
152
+ if abs(shift_amount) > len(self._bits):
153
+ new_bits = [fill] * len(self._bits)
154
+ elif shift_amount > 0:
155
+ new_bits = [fill] * shift_amount + self._bits[:-shift_amount]
156
+ else:
157
+ new_bits = self._bits[-shift_amount:] + [fill] * (-shift_amount)
158
+ return BitArray(new_bits)
159
+
160
+ def copy(self) -> BitArray:
161
+ """Create a copy of the bit array.
162
+
163
+ Returns:
164
+ BitArray: A new BitArray with the same bits.
165
+ """
166
+ return BitArray(self._bits.copy())
167
+
168
+ def __len__(self) -> int:
169
+ """Return the length of the bit array."""
170
+ return len(self._bits)
171
+
172
+ @overload
173
+ def __getitem__(self, index: int) -> bool: ...
174
+ @overload
175
+ def __getitem__(self, index: slice) -> BitArray: ...
176
+
177
+ def __getitem__(self, index: int | slice) -> bool | BitArray:
178
+ """Get an item or slice from the bit array."""
179
+ if isinstance(index, slice):
180
+ return BitArray(self._bits[index])
181
+ return self._bits[index]
182
+
183
+ @overload
184
+ def __setitem__(self, index: int, value: bool) -> None: ...
185
+ @overload
186
+ def __setitem__(self, index: slice, value: BitArray | list[bool]) -> None: ...
187
+
188
+ def __setitem__(
189
+ self, index: int | slice, value: bool | list[bool] | BitArray
190
+ ) -> None:
191
+ """Set an item or slice in the bit array."""
192
+ if isinstance(index, slice):
193
+ if isinstance(value, BitArray):
194
+ self._bits[index] = value._bits
195
+ elif isinstance(value, list):
196
+ self._bits[index] = value
197
+ else:
198
+ raise TypeError("Cannot assign a single bool to a slice")
199
+ return
200
+ if isinstance(value, bool):
201
+ self._bits[index] = value
202
+ else:
203
+ raise TypeError("Cannot assign a list or BitArray to a single index")
204
+
205
+ def __iter__(self) -> Iterator[bool]:
206
+ """Iterate over the bits in the array."""
207
+ return iter(self._bits)
208
+
209
+ def __add__(self, other: BitArray | list[bool]) -> BitArray:
210
+ """Concatenate two bit arrays."""
211
+ if isinstance(other, BitArray):
212
+ return BitArray(self._bits + other._bits)
213
+ return BitArray(self._bits + other)
214
+
215
+ def __radd__(self, other: list[bool]) -> BitArray:
216
+ """Reverse concatenation with a list."""
217
+ return BitArray(other + self._bits)
218
+
219
+ def __eq__(self, other: object) -> bool:
220
+ """Check equality with another BitArray or list."""
221
+ if isinstance(other, BitArray):
222
+ return self._bits == other._bits
223
+ if isinstance(other, list):
224
+ return self._bits == other
225
+ return False
226
+
227
+ def __bool__(self) -> bool:
228
+ """Return True if any bit is set."""
229
+ return any(self._bits)
230
+
231
+ def __repr__(self) -> str:
232
+ """Return a string representation of the BitArray."""
233
+ return f"BitArray({self._bits})"
234
+
235
+ def __str__(self) -> str:
236
+ """Return a string representation of the bits."""
237
+ return "".join("1" if bit else "0" for bit in self._bits)
238
+
239
+ def any(self) -> bool:
240
+ """Return True if any bit is set to True."""
241
+ return any(self._bits)
242
+
243
+ def all(self) -> bool:
244
+ """Return True if all bits are set to True."""
245
+ return all(self._bits)
246
+
247
+ def count(self, value: bool = True) -> int:
248
+ """Count the number of bits set to the specified value."""
249
+ return self._bits.count(value)
250
+
251
+ def reverse(self) -> BitArray:
252
+ """Return a new BitArray with the bits in reverse order."""
253
+ return BitArray(self._bits[::-1])