-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsigfig.py
More file actions
48 lines (43 loc) · 1.29 KB
/
sigfig.py
File metadata and controls
48 lines (43 loc) · 1.29 KB
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
#!/usr/bin/python
############################################
# #
# Write by: Christian Contreras-Campana #
# email: christian.contreras@desy.de #
# Date: 05.08.2016 #
# #
############################################
'''Module provides functionality for working with significant figures.'''
import types, re, string
epat = re.compile(r'^([^e]+)e(.+)$')
def round_sig(x, n):
'''Round floating point x to n significant figures'''
if type(n) is not types.IntType:
raise TypeError, "n must be an integer"
try:
x = float(x)
except:
raise TypeError, "x must be a floating point object"
form = "%0." + str(n-1) + "e"
st = form % x
num,expo = epat.findall(st)[0]
expo = int(expo)
fs = string.split(num,'.')
if len(fs) < 2:
fs = [fs[0],""]
if expo == 0:
return num
elif expo > 0:
if len(fs[1]) < expo:
fs[1] += "0"*(expo-len(fs[1]))
st = fs[0]+fs[1][0:expo]
if len(fs[1][expo:]) > 0:
st += '.'+fs[1][expo:]
return st
else:
expo = -expo
if fs[0][0] == '-':
fs[0] = fs[0][1:]
sign = "-"
else:
sign = ""
return sign+"0."+"0"*(expo-1)+fs[0]+fs[1]