-
Notifications
You must be signed in to change notification settings - Fork 2
[decimal] Implement scaleb, bit_count, __float__, fma, etc
#183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,6 +48,7 @@ struct BigInt( | |
| Absable, | ||
| Comparable, | ||
| Copyable, | ||
| FloatableRaising, | ||
| IntableRaising, | ||
| Movable, | ||
| Representable, | ||
|
|
@@ -466,6 +467,18 @@ struct BigInt( | |
| """ | ||
| return self.to_int() | ||
|
|
||
| fn __float__(self) raises -> Float64: | ||
| """Converts the BigInt to a floating-point number. | ||
|
|
||
| Matches Python's `float(n)` for `int` objects. | ||
|
|
||
| Note: Large values may lose precision or overflow to `inf`. | ||
|
|
||
| Returns: | ||
| The value as a Float64. | ||
| """ | ||
| return Float64(String(self)) | ||
|
|
||
| fn __str__(self) -> String: | ||
| """Returns a decimal string representation of the BigInt.""" | ||
| return self.to_string() | ||
|
|
@@ -1238,6 +1251,32 @@ struct BigInt( | |
|
|
||
| return (n_words - 1) * 32 + bits_in_msw | ||
|
|
||
| fn bit_count(self) -> Int: | ||
| """Returns the number of ones in the binary representation of the | ||
| absolute value (population count). | ||
|
|
||
| Matches Python 3.10+ `int.bit_count()`. | ||
|
|
||
| Returns: | ||
| The number of set bits in the magnitude, or 0 if the value is zero. | ||
|
|
||
| Examples: | ||
|
|
||
| ``` | ||
| BigInt(13).bit_count() # 3 (13 = 0b1101) | ||
| BigInt(-7).bit_count() # 3 (7 = 0b111) | ||
| BigInt(0).bit_count() # 0 | ||
| ``` | ||
| """ | ||
| var count = 0 | ||
| for i in range(len(self.words)): | ||
| var w = self.words[i] | ||
| # Kernighan's bit-counting trick | ||
| while w != 0: | ||
| w &= w - 1 | ||
| count += 1 | ||
| return count | ||
|
Comment on lines
+1271
to
+1278
|
||
|
|
||
| fn number_of_words(self) -> Int: | ||
| """Returns the number of words in the magnitude.""" | ||
| return len(self.words) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
__float__converts viaFloat64(String(self)), which forces a full base-2^32 → decimal string conversion and then reparses it. For very largeBigIntvalues this is substantially more expensive (time + memory) than converting from the binary words directly; consider a word-based Float64 conversion to avoid the intermediate string if this becomes a hotspot.