MCPcopy Index your code
hub / github.com/python/cpython / _round_to_figures

Function _round_to_figures

Lib/fractions.py:102–138  ·  view source on GitHub ↗

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: bool, significand: int, exponent: int) representing the rounded value (-1)**sign

(n, d, figures)

Source from the content-addressed store, hash-verified

100
101
102def _round_to_figures(n, d, figures):
103 """Round a rational number to a given number of significant figures.
104
105 Rounds the rational number n/d to the given number of significant figures
106 using the round-ties-to-even rule, and returns a triple
107 (sign: bool, significand: int, exponent: int) representing the rounded
108 value (-1)**sign * significand * 10**exponent.
109
110 In the special case where n = 0, returns a significand of zero and
111 an exponent of 1 - figures, for compatibility with formatting.
112 Otherwise, the returned significand satisfies
113 10**(figures - 1) <= significand < 10**figures.
114
115 d must be positive, but n and d need not be relatively prime.
116 figures must be positive.
117 """
118 # Special case for n == 0.
119 if n == 0:
120 return False, 0, 1 - figures
121
122 # Find integer m satisfying 10**(m - 1) <= abs(n)/d <= 10**m. (If abs(n)/d
123 # is a power of 10, either of the two possible values for m is fine.)
124 str_n, str_d = str(abs(n)), str(d)
125 m = len(str_n) - len(str_d) + (str_d <= str_n)
126
127 # Round to a multiple of 10**(m - figures). The significand we get
128 # satisfies 10**(figures - 1) <= significand <= 10**figures.
129 exponent = m - figures
130 sign, significand = _round_to_exponent(n, d, exponent)
131
132 # Adjust in the case where significand == 10**figures, to ensure that
133 # 10**(figures - 1) <= significand < 10**figures.
134 if len(str(significand)) == figures + 1:
135 significand //= 10
136 exponent += 1
137
138 return sign, significand, exponent
139
140
141# Pattern for matching non-float-style format specifications.

Callers 1

_format_float_styleMethod · 0.85

Calls 3

strFunction · 0.85
absFunction · 0.85
_round_to_exponentFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…