Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
8cf8d31
Add '.f' formatting for Fraction objects
mdickinson Dec 3, 2022
e9db697
Add support for % and F format specifiers
mdickinson Dec 3, 2022
6491b04
Add support for 'z' flag
mdickinson Dec 4, 2022
4551468
Tidy up of business logic
mdickinson Dec 4, 2022
43d34fc
Add support for 'e' presentation type
mdickinson Dec 4, 2022
f8dfcb9
Add support for 'g' presentation type; tidy
mdickinson Dec 4, 2022
6bfbc6c
Tidying
mdickinson Dec 10, 2022
48629b7
Add news entry
mdickinson Dec 10, 2022
3d21af2
Add documentation
mdickinson Dec 10, 2022
c86a57e
Add what's new entry
mdickinson Dec 10, 2022
b521efb
Fix backticks:
mdickinson Dec 10, 2022
aac576e
Fix more missing backticks
mdickinson Dec 10, 2022
b9ee0ff
Fix indentation
mdickinson Dec 10, 2022
1c8b8a9
Wordsmithing for consistency with other method definitions
mdickinson Dec 10, 2022
9dbde3b
Add link to the format specification mini-language
mdickinson Dec 10, 2022
2dd48bb
Fix: not true that thousands separators cannot have an effect for the…
mdickinson Dec 10, 2022
983726f
Fix typo in comment
mdickinson Dec 10, 2022
b7e5129
Tweak docstring and comments for _round_to_exponent
mdickinson Dec 21, 2022
cb5e234
Second pass on docstring and comments for _round_to_figures
mdickinson Dec 21, 2022
907487e
Add tests for the corner case of zero minimum width + alignment
mdickinson Dec 21, 2022
aba35f3
Tests for the case of zero padding _and_ a zero minimum width
mdickinson Dec 21, 2022
fc4d3b5
Cleanup of __format__ method
mdickinson Dec 21, 2022
4ccdf94
Add test cases from original issue and discussion thread
mdickinson Dec 21, 2022
b358b37
Merge branch 'main' into fraction-format
mdickinson Dec 21, 2022
67e020c
Tighten up the regex - extra leading zeros not permitted
mdickinson Dec 21, 2022
e240c70
Merge remote-tracking branch 'mdickinson/fraction-format' into fracti…
mdickinson Dec 21, 2022
111c41f
Add tests for a few more fill character corner cases
mdickinson Dec 21, 2022
d8cc3d6
Merge remote-tracking branch 'upstream/main' into fraction-format
mdickinson Jan 22, 2023
fff3751
Add testcases for no presentation type with an integral fraction
mdickinson Jan 22, 2023
0b8bfa6
Rename the regex to allow for future API expansion
mdickinson Jan 22, 2023
54ed402
Tweak comment
mdickinson Jan 22, 2023
e3a5fd2
Tweak algorithm comments
mdickinson Jan 22, 2023
098d34c
Fix incorrect acceptance of Z instead of z
mdickinson Jan 22, 2023
2c476a2
Use consistent quote style in tests
mdickinson Jan 22, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Tidying
  • Loading branch information
mdickinson committed Dec 10, 2022
commit 6bfbc6c10087b6604e884bf1f10113247ce45f76
180 changes: 107 additions & 73 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,76 @@ def _hash_algorithm(numerator, denominator):
\s*\Z # and optional whitespace to finish
""", re.VERBOSE | re.IGNORECASE)

# Pattern for matching format specification; only supports 'e', 'E', 'f', 'F'
# and '%' presentation types.

# Helpers for formatting

def _round_to_exponent(n, d, exponent, no_neg_zero=False):
"""Round a rational number to an integer multiple of a power of 10.

Rounds the rational number n/d to the nearest integer multiple of
10**exponent using the round-ties-to-even rule, and returns a
pair (sign, significand) representing the rounded value
(-1)**sign * significand.
Comment thread
mdickinson marked this conversation as resolved.
Outdated

d must be positive, but n and d need not be relatively prime.

If no_neg_zero is true, then the returned sign will always be False
for a zero result. Otherwise, the sign is based on the sign of the input.
"""
if exponent >= 0:
d *= 10**exponent
else:
n *= 10**-exponent

# The divmod quotient rounds ties towards positive infinity; we then adjust
# as needed for round-ties-to-even behaviour.
q, r = divmod(n + (d >> 1), d)
if r == 0 and d & 1 == 0: # Tie
q &= -2

sign = q < 0 if no_neg_zero else n < 0
return sign, abs(q)


def _round_to_figures(n, d, figures):
"""Round a rational number to a given number of significant figures.

Rounds the rational number n/d to the given number of significant figures
using the round-ties-to-even rule, and returns a triple (sign, significand,
exponent) representing the rounded value (-1)**sign * significand *
10**exponent.

d must be positive, but n and d need not be relatively prime.
figures must be positive.

In the special case where n = 0, returns an exponent of 1 - figures, for
compatibility with formatting; the significand will be zero. Otherwise,
the significand satisfies 10**(figures - 1) <= significand < 10**figures.
"""
# Find integer m satisfying 10**(m - 1) <= abs(self) <= 10**m if self
# is nonzero, with m = 1 if self = 0. (The latter choice is a little
# arbitrary, but gives the "right" results when formatting zero.)
if n == 0:
m = 1
else:
str_n, str_d = str(abs(n)), str(d)
m = len(str_n) - len(str_d) + (str_d <= str_n)

# Round to a multiple of 10**(m - figures). The result will satisfy either
# significand == 0 or 10**(figures - 1) <= significand <= 10**figures.
exponent = m - figures
sign, significand = _round_to_exponent(n, d, exponent)

# Adjust in the case where significand == 10**figures.
if len(str(significand)) == figures + 1:
significand //= 10
exponent += 1

return sign, significand, exponent


# Pattern for matching format specification; supports 'e', 'E', 'f', 'F',
# 'g', 'G' and '%' presentation types.
_FORMAT_SPECIFICATION_MATCHER = re.compile(r"""
(?:
(?P<fill>.)?
Expand All @@ -78,8 +146,8 @@ def _hash_algorithm(numerator, denominator):
(?P<sign>[-+ ]?)
(?P<no_neg_zero>z)?
(?P<alt>\#)?
(?P<zeropad>0(?=\d))?
(?P<minimumwidth>\d+)?
(?P<zeropad>0(?=\d))? # use lookahead so that an isolated '0' is treated
(?P<minimumwidth>\d+)? # as minimum width rather than the zeropad flag
(?P<thousands_sep>[,_])?
(?:\.(?P<precision>\d+))?
(?P<presentation_type>[efg%])
Expand Down Expand Up @@ -327,35 +395,6 @@ def __str__(self):
else:
return '%s/%s' % (self._numerator, self._denominator)

def _round_to_sig_figs(self, figures):
"""Round a positive fraction to a given number of significant figures.

Returns a pair (significand, exponent) of integers such that
significand * 10**exponent gives a rounded approximation to self, and
significand lies in the range 10**(figures - 1) <= significand <
10**figures.
"""
if not (self > 0 and figures > 0):
raise ValueError("Expected self and figures to be positive")

# Find integer m satisfying 10**(m - 1) <= self <= 10**m.
str_n, str_d = str(self.numerator), str(self.denominator)
m = len(str_n) - len(str_d) + (str_d <= str_n)

# Find best approximation significand * 10**exponent to self, with
# 10**(figures - 1) <= significand <= 10**figures.
exponent = m - figures
significand = round(
self / 10**exponent if exponent >= 0 else self * 10**-exponent
)

# Adjust in the case where significand == 10**figures.
if len(str(significand)) == figures + 1:
significand //= 10
exponent += 1

return significand, exponent

def __format__(self, format_spec, /):
"""Format this fraction according to the given format specification."""

Expand All @@ -377,66 +416,61 @@ def __format__(self, format_spec, /):
f"for object of type {type(self).__name__!r}; "
"can't use explicit alignment when zero-padding"
)

fill = match["fill"] or " "
align = match["align"] or ">"
pos_sign = "" if match["sign"] == "-" else match["sign"]
neg_zero_ok = not match["no_neg_zero"]
no_neg_zero = bool(match["no_neg_zero"])
alternate_form = bool(match["alt"])
zeropad = bool(match["zeropad"])
minimumwidth = int(match["minimumwidth"] or "0")
thousands_sep = match["thousands_sep"]
precision = int(match["precision"] or "6")
presentation_type = match["presentation_type"]
trim_zeros = presentation_type in "gG" and not alternate_form
trim_dot = not alternate_form
trim_point = not alternate_form
exponent_indicator = "E" if presentation_type in "EFG" else "e"

# Record sign, then work with absolute value.
negative = self < 0
self = abs(self)

# Round to get the digits we need; also compute the suffix.
if presentation_type == "f" or presentation_type == "F":
significand = round(self * 10**precision)
point_pos = precision
suffix = ""
elif presentation_type == "%":
significand = round(self * 10**(precision + 2))
# Round to get the digits we need, figure out where to place the point,
# and decide whether to use scientific notation.
n, d = self._numerator, self._denominator
if presentation_type in "fF%":
exponent = -precision - (2 if presentation_type == "%" else 0)
Comment thread
mdickinson marked this conversation as resolved.
Outdated
negative, significand = _round_to_exponent(
n, d, exponent, no_neg_zero)
scientific = False
point_pos = precision
else: # presentation_type in "eEgG"
figures = (
max(precision, 1)
if presentation_type in "gG"
else precision + 1
)
negative, significand, exponent = _round_to_figures(n, d, figures)
scientific = (
presentation_type in "eE"
or exponent > 0 or exponent + figures <= -4
)
point_pos = figures - 1 if scientific else -exponent

# Get the suffix - the part following the digits.
if presentation_type == "%":
suffix = "%"
elif presentation_type in "eEgG":
if presentation_type in "gG":
figures = max(precision, 1)
else:
figures = precision + 1
if self:
significand, exponent = self._round_to_sig_figs(figures)
else:
significand, exponent = 0, 1 - figures
if presentation_type in "gG" and -4 - figures < exponent <= 0:
point_pos = -exponent
suffix = ""
else:
point_pos = figures - 1
suffix = f"{exponent_indicator}{exponent + point_pos:+03d}"
elif scientific:
suffix = f"{exponent_indicator}{exponent + point_pos:+03d}"
else:
# It shouldn't be possible to get here.
raise ValueError(
f"unknown presentation type {presentation_type!r}"
)
suffix = ""

# Assemble the output: before padding, it has the form
# f"{sign}{leading}{trailing}", where `leading` includes thousands
# separators if necessary, and `trailing` includes the decimal
# separator where appropriate.
digits = f"{significand:0{point_pos + 1}d}"
sign = "-" if negative and (significand or neg_zero_ok) else pos_sign
leading = digits[:len(digits) - point_pos]
frac_part = digits[len(digits) - point_pos:]
sign = "-" if negative else pos_sign
leading = digits[: len(digits) - point_pos]
frac_part = digits[len(digits) - point_pos :]
if trim_zeros:
frac_part = frac_part.rstrip("0")
separator = "" if trim_dot and not frac_part else "."
separator = "" if trim_point and not frac_part else "."
trailing = separator + frac_part + suffix

# Do zero padding if required.
Expand All @@ -452,19 +486,19 @@ def __format__(self, format_spec, /):
if thousands_sep:
first_pos = 1 + (len(leading) - 1) % 3
leading = leading[:first_pos] + "".join(
thousands_sep + leading[pos:pos+3]
thousands_sep + leading[pos : pos + 3]
for pos in range(first_pos, len(leading), 3)
)

# Pad if necessary and return.
# Pad with fill character if necessary and return.
body = leading + trailing
padding = fill * (minimumwidth - len(sign) - len(body))
if align == ">":
return padding + sign + body
elif align == "<":
return sign + body + padding
elif align == "^":
half = len(padding)//2
half = len(padding) // 2
return padding[:half] + sign + body + padding[half:]
else: # align == "="
return sign + padding + body
Expand Down
29 changes: 20 additions & 9 deletions Lib/test/test_fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,12 +947,23 @@ def test_format_f_presentation_type(self):
(F(-2, 3), ' .2f', '-0.67'),
# Formatting to zero places
(F(1, 2), '.0f', '0'),
(F(-1, 2), '.0f', '-0'),
(F(22, 7), '.0f', '3'),
(F(-22, 7), '.0f', '-3'),
# Formatting to zero places, alternate form
(F(1, 2), '#.0f', '0.'),
(F(-1, 2), '#.0f', '-0.'),
(F(22, 7), '#.0f', '3.'),
(F(-22, 7), '#.0f', '-3.'),
# z flag for suppressing negative zeros
(F('-0.001'), 'z.2f', '0.00'),
(F('-0.001'), '-z.2f', '0.00'),
(F('-0.001'), '+z.2f', '+0.00'),
(F('-0.001'), ' z.2f', ' 0.00'),
(F('0.001'), 'z.2f', '0.00'),
(F('0.001'), '-z.2f', '0.00'),
(F('0.001'), '+z.2f', '+0.00'),
(F('0.001'), ' z.2f', ' 0.00'),
# Corner-case: leading zeros are allowed in the precision
(F(2, 3), '.02f', '0.67'),
(F(22, 7), '.000f', '3'),
Expand Down Expand Up @@ -1040,15 +1051,6 @@ def test_format_f_presentation_type(self):
# is being inserted programmatically: spec = f'{width}.2f'.
(F('12.34'), '0.2f', '12.34'),
(F('12.34'), 'X>0.2f', '12.34'),
# z flag for suppressing negative zeros
(F('-0.001'), 'z.2f', '0.00'),
(F('-0.001'), '-z.2f', '0.00'),
(F('-0.001'), '+z.2f', '+0.00'),
(F('-0.001'), ' z.2f', ' 0.00'),
(F('0.001'), 'z.2f', '0.00'),
(F('0.001'), '-z.2f', '0.00'),
(F('0.001'), '+z.2f', '+0.00'),
(F('0.001'), ' z.2f', ' 0.00'),
# "F" should work identically to "f"
(F(22, 7), '.5F', '3.14286'),
# %-specifier
Expand Down Expand Up @@ -1088,6 +1090,15 @@ def test_format_g_presentation_type(self):
(F('9.99999e+2'), '.4g', '1000'),
(F('9.99999e-8'), '.4g', '1e-07'),
(F('9.99999e+8'), '.4g', '1e+09'),
# Check round-ties-to-even behaviour
(F('-0.115'), '.2g', '-0.12'),
(F('-0.125'), '.2g', '-0.12'),
(F('-0.135'), '.2g', '-0.14'),
(F('-0.145'), '.2g', '-0.14'),
(F('0.115'), '.2g', '0.12'),
(F('0.125'), '.2g', '0.12'),
(F('0.135'), '.2g', '0.14'),
(F('0.145'), '.2g', '0.14'),
# Trailing zeros and decimal point suppressed by default ...
(F(0), '.6g', '0'),
(F('123.400'), '.6g', '123.4'),
Expand Down