-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathto_precision.py
301 lines (231 loc) · 9.86 KB
/
to_precision.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""to_precison"""
__author__ = """
William Rusnack github.com/BebeSparkelSparkel linkedin.com/in/williamrusnack williamrusnack@gmail.com
Eric Moyer github.com/epmoyer eric@lemoncrab.com
Thomas Hladish https://github.com/tjhladish tjhladish@utexas.edu
"""
from math import floor as _floor
from math import log10 as _log10
import math as _math
def std_notation(value, precision):
"""
standard notation (US version)
ref: http://www.mathsisfun.com/definitions/standard-notation.html
returns a string of value with the proper precision
ex:
std_notation(5, 2) => '5.0'
std_notation(5.36, 2) => '5.4'
std_notation(5360, 2) => '5400'
std_notation(0.05363, 3) => '0.0536'
created by William Rusnack
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
"""
return to_precision(value, precision, notation='std')
def sci_notation(value, precision, delimiter='e'):
"""
scientific notation
ref: https://www.mathsisfun.com/numbers/scientific-notation.html
returns a string of value with the proper precision and 10s exponent
delimiter is placed between the decimal value and 10s exponent
ex:
sci_notation(123, 1, 'E') => '1E2'
sci_notation(123, 3, 'E') => '1.23E2'
sci_notation(.126, 2, 'E') => '1.3E-1'
created by William Rusnack
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
"""
return to_precision(value, precision, notation='sci', delimiter=delimiter)
def eng_notation(value, precision, delimiter='e'):
"""
engineering notation
ref: http://www.mathsisfun.com/definitions/engineering-notation.html
returns a string of value with the proper precision and 10s exponent that is divisible by 3
delimiter is placed between the decimal value and 10s exponent
ex:
sci_notation(123, 1, 'E') => '100E0'
sci_notation(1230, 3, 'E') => '1.23E3'
sci_notation(.126, 2, 'E') => '120E-3'
created by William Rusnack
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
"""
return to_precision(value, precision, notation='eng', delimiter=delimiter)
def auto_notation(value, precision, delimiter='e'):
"""
Automatically selects between standard notation (US version) and scientific notation.
Values in the range 0.001 < abs(value) < 1000 return standard notation.
http://www.mathsisfun.com/definitions/standard-notation.html
https://www.mathsisfun.com/numbers/scientific-notation.html
returns a string of value with the proper precision
ex:
auto_notation(123, 4) => '123.4'
std_notation(1234, 4) => '1.234e3'
"""
if _math.isnan(value):
return 'nan'
return to_precision(value, precision, notation='auto', delimiter=delimiter)
def to_precision(value,
precision,
notation='auto',
delimiter='e',
auto_limit=3,
strip_zeros=False,
preserve_integer=False):
"""
converts a value to the specified notation and precision
value - any type that can be converted to a float
precision - integer that is greater than zero
notation - string
'auto' - selects standard notation when abs(power) < auto_limit else
returns scientific notation.
'sci' or 'scientific' - returns scientific notation
ref: https://www.mathsisfun.com/numbers/scientific-notation.html
'eng' or 'engineering' - returns engineering notation
ref: http://www.mathsisfun.com/definitions/engineering-notation.html
'std' or 'standard' - returns standard notation
ref: http://www.mathsisfun.com/definitions/standard-notation.html
delimiter - is placed between the decimal value and 10s exponent
auto_limit - integer. When abs(power) exceeds this limit, 'auto'
mode will return scientific notation.
strip_zeros - if true, trailing decimal zeros will be removed.
preserve_integer - if true, 'std' will preserve all digits when returning
values that have no decimal component.
"""
if _math.isnan(value):
return 'nan'
_, _, _, ten_power = _sci_decompose(value, precision)
if notation == 'auto':
if abs(ten_power) < auto_limit:
converter = _std_notation
else:
converter = _sci_notation
elif notation in ('sci', 'scientific'):
converter = _sci_notation
elif notation in ('eng', 'engineering'):
converter = _eng_notation
elif notation in ('std', 'standard'):
converter = _std_notation
else:
raise ValueError('Unknown notation: ' + str(notation))
return converter(value, precision, delimiter, strip_zeros, preserve_integer)
def _std_notation(value, precision, _, strip_zeros, preserve_integer):
"""
standard notation (US version)
ref: http://www.mathsisfun.com/definitions/standard-notation.html
returns a string of value with the proper precision
strip_zeros - if true, trailing decimal zeros will be removed.
preserve_integer - if true, 'std' will preserve all digits when returning
values that have no decimal component.
"""
sig_digits, power, is_neg = _number_profile(value, precision)
result = ('-' if is_neg else '') + _place_dot(sig_digits, power, strip_zeros)
if preserve_integer and '.' not in result:
# Result was an integer, preserve all digits
result = '{:0.0f}'.format(value)
return result
def _sci_notation(value, precision, delimiter, strip_zeros, _):
"""
scientific notation
ref: https://www.mathsisfun.com/numbers/scientific-notation.html
returns a string of value with the proper precision and 10s exponent
delimiter is placed between the decimal value and 10s exponent
strip_zeros - if true, trailing decimal zeros will be removed.
"""
is_neg, sig_digits, dot_power, ten_power = _sci_decompose(value, precision)
return ('-' if is_neg else '') + _place_dot(sig_digits, dot_power, strip_zeros) + delimiter + str(ten_power)
def _eng_notation(value, precision, delimiter, strip_zeros, _):
"""
engineering notation
ref: http://www.mathsisfun.com/definitions/engineering-notation.html
returns a string of value with the proper precision and 10s exponent that is divisible by 3
delimiter is placed between the decimal value and 10s exponent
strip_zeros - if true, trailing decimal zeros will be removed.
"""
is_neg, sig_digits, dot_power, ten_power = _sci_decompose(value, precision)
eng_power = int(3 * _floor(ten_power / 3))
eng_dot = dot_power + ten_power - eng_power
return ('-' if is_neg else '') + _place_dot(sig_digits, eng_dot, strip_zeros) + delimiter + str(eng_power)
def _sci_decompose(value, precision):
"""
returns the properties for to construct a scientific notation number
used in sci_notation and eng_notation
created by William Rusnack
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
"""
value = float(value)
sig_digits, power, is_neg = _number_profile(value, precision)
dot_power = -(precision - 1)
ten_power = power + precision - 1
return is_neg, sig_digits, dot_power, ten_power
def _place_dot(digits, power, strip_zeros=False):
"""
places the dot in the correct spot in the digits
if the dot is outside the range of the digits zeros will be added
if strip_zeros is set, trailing decimal zeros will be removed
ex:
_place_dot('123', 2, False) => '12300'
_place_dot('123', -2, False) => '1.23'
_place_dot('123', 3, False) => '0.123'
_place_dot('123', 5, False) => '0.00123'
_place_dot('120', 0, False) => '120.'
_place_dot('1200', -2, False) => '12.00'
_place_dot('1200', -2, True ) => '12'
_place_dot('1200', -1, False) => '120.0'
_place_dot('1200', -1, True ) => '120'
created by William Rusnack
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
"""
if power > 0:
out = digits + '0' * power
elif power < 0:
power = abs(power)
precision = len(digits)
if power < precision:
out = digits[:-power] + '.' + digits[-power:]
else:
out = '0.' + '0' * (power - precision) + digits
else:
out = digits + ('.' if digits[-1] == '0' and len(digits) > 1 else '')
if strip_zeros and '.' in out:
out = out.rstrip('0').rstrip('.')
return out
def _number_profile(value, precision):
"""
returns:
string of significant digits
10s exponent to get the dot to the proper location in the significant digits
bool that's true if value is less than zero else false
created by William Rusnack
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
contributions by Thomas Hladish
github.com/tjhladish
Issue: github.com/BebeSparkelSparkel/to-precision/issues/5
"""
value = float(value)
is_neg = value < 0
value = abs(value)
if value == 0:
sig_digits = '0' * precision
power = -(1 - precision)
else:
if _math.isnan(value):
return _math.nan
power = -1 * _floor(_log10(value)) + precision - 1
value_power = value * 10.0 ** power
if value < 1 and \
_floor(_log10(int(round(value_power)))) > \
_floor(_log10(int(value_power))):
power -= 1
sig_digits = str(int(round(value * 10.0 ** power))) # cannot use value_power because power is changed
return sig_digits, int(-power), is_neg