Skip to content

Commit 30d5c6a

Browse files
committed
Fix overflow
1 parent 48e16f4 commit 30d5c6a

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/gfloat/printing.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,22 @@ def float_pow2str(v: float, min_exponent: float = -np.inf) -> str:
2121
if not np.isfinite(v):
2222
return str(v)
2323

24-
s = np.sign(v)
24+
signstr = "-" if np.signbit(v) else ""
25+
2526
x = np.abs(v)
26-
e = np.floor(np.log2(x))
27-
sig = x * 2.0**-e
27+
e = int(np.floor(np.log2(x)))
28+
sig = np.ldexp(x, -e)
2829
if e < min_exponent:
29-
sig *= 2.0 ** (e - min_exponent)
30+
sig = np.ldexp(sig, e - min_exponent)
3031
e = min_exponent
3132

33+
pow2str = f"2^{int(e):d}"
34+
3235
significand = fractions.Fraction(sig)
33-
return ("-" if s < 0 else "") + f"{significand}*2^{int(e):d}"
36+
if significand == 1:
37+
return signstr + pow2str
38+
else:
39+
return signstr + f"{significand}*{pow2str}"
3440

3541

3642
def float_tilde_unless_roundtrip_str(v: float, width: int = 14, d: int = 8) -> str:

0 commit comments

Comments
 (0)