Skip to content

Commit b2c8e40

Browse files
committed
Illustrate bias with limited-precision inputs and SR bits
1 parent d67adb0 commit b2c8e40

File tree

3 files changed

+603
-24
lines changed

3 files changed

+603
-24
lines changed

docs/source/05-stochastic-rounding.ipynb

Lines changed: 586 additions & 22 deletions
Large diffs are not rendered by default.

src/gfloat/round_ndarray.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,18 @@ def round_ndarray(
8888
should_round_away = (delta > 0.5) | ((delta == 0.5) & code_is_odd)
8989
case RoundMode.Stochastic:
9090
assert srbits is not None
91-
should_round_away = delta > (0.5 + srbits) * 2.0**-srnumbits
91+
## RTNE delta to srbits
92+
d = delta * 2.0**srnumbits
93+
floord = np.floor(d).astype(np.int64)
94+
d = floord + ((d - floord > 0.5) | ((d - floord == 0.5) & _isodd(floord)))
95+
96+
should_round_away = d > srbits
9297
case RoundMode.StochasticFast:
9398
assert srbits is not None
9499
should_round_away = delta > srbits * 2.0**-srnumbits
100+
case RoundMode.StochasticNearly:
101+
assert srbits is not None
102+
should_round_away = delta > (2 * srbits + 1) * 2.0 ** -(1 + srnumbits)
95103

96104
isignificand = np.where(should_round_away, isignificand + 1, isignificand)
97105

src/gfloat/types.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,14 @@ class RoundMode(Enum):
1717
TiesToEven = 4 #: Round to nearest, ties to even
1818
TiesToAway = 5 #: Round to nearest, ties away from zero
1919
Stochastic = 6 #: Stochastic rounding
20-
StochasticFast = 7 #: Stochastic rounding - possibly faster, but biased.
20+
StochasticFast = 7 #: Stochastic rounding - faster, but biased.
21+
StochasticNearly = 8 #: Stochastic rounding - incorrect, see [Note 1].
22+
23+
24+
# [Note 1]:
25+
# StochasticNearly implements a stochastic rounding scheme that is unbiased in
26+
# infinite precision, but biased when the quantity to be rounded is computed to
27+
# a finite precision.
2128

2229

2330
class FloatClass(Enum):

0 commit comments

Comments
 (0)