Debian Codegraph @

cpython27/Lib/fpformat.py

raw symbols SCIP
1 """General floating point formatting functions.
2
3 Functions:
4 fix(x, digits_behind)
5 sci(x, digits_behind)
6
7 Each takes a number or a string and a number of digits as arguments.
8
9 Parameters:
10 x: number to be formatted; or a string resembling a number
11 digits_behind: number of digits behind the decimal point
12 """
13 from warnings import warnpy3k
14 warnpy3k("the fpformat module has been removed in Python 3.0", stacklevel=2)
15 del warnpy3k
16
17 import re
18
19 __all__ = ["fix","sci","NotANumber"]
20
21 # Compiled regular expression to "decode" a number
22 decoder = re.compile(r'^([-+]?)(\d*)((?:\.\d*)?)(([eE][-+]?\d+)?)$')
23 # \0 the whole thing
24 # \1 leading sign or empty
25 # \2 digits left of decimal point
26 # \3 fraction (empty or begins with point)
27 # \4 exponent part (empty or begins with 'e' or 'E')
28
29 try:
30 class NotANumber(ValueError):
31 pass
32 except TypeError:
33 NotANumber = 'fpformat.NotANumber'
34
35 def extract(s):
36 """Return (sign, intpart, fraction, expo) or raise an exception:
37 sign is '+' or '-'
38 intpart is 0 or more digits beginning with a nonzero
39 fraction is 0 or more digits
40 expo is an integer"""
41 res = decoder.match(s)
42 if res is None: raise NotANumber, s
43 sign, intpart, fraction, exppart = res.group(1,2,3,4)
44 intpart = intpart.lstrip('0');
45 if sign == '+': sign = ''
46 if fraction: fraction = fraction[1:]
47 if exppart: expo = int(exppart[1:])
48 else: expo = 0
49 return sign, intpart, fraction, expo
50
51 def unexpo(intpart, fraction, expo):
52 """Remove the exponent by changing intpart and fraction."""
53 if expo > 0: # Move the point left
54 f = len(fraction)
55 intpart, fraction = intpart + fraction[:expo], fraction[expo:]
56 if expo > f:
57 intpart = intpart + '0'*(expo-f)
58 elif expo < 0: # Move the point right
59 i = len(intpart)
60 intpart, fraction = intpart[:expo], intpart[expo:] + fraction
61 if expo < -i:
62 fraction = '0'*(-expo-i) + fraction
63 return intpart, fraction
64
65 def roundfrac(intpart, fraction, digs):
66 """Round or extend the fraction to size digs."""
67 f = len(fraction)
68 if f <= digs:
69 return intpart, fraction + '0'*(digs-f)
70 i = len(intpart)
71 if i+digs < 0:
72 return '0'*-digs, ''
73 total = intpart + fraction
74 nextdigit = total[i+digs]
75 if nextdigit >= '5': # Hard case: increment last digit, may have carry!
76 n = i + digs - 1
77 while n >= 0:
78 if total[n] != '9': break
79 n = n-1
80 else:
81 total = '0' + total
82 i = i+1
83 n = 0
84 total = total[:n] + chr(ord(total[n]) + 1) + '0'*(len(total)-n-1)
85 intpart, fraction = total[:i], total[i:]
86 if digs >= 0:
87 return intpart, fraction[:digs]
88 else:
89 return intpart[:digs] + '0'*-digs, ''
90
91 def fix(x, digs):
92 """Format x as [-]ddd.ddd with 'digs' digits after the point
93 and at least one digit before.
94 If digs <= 0, the point is suppressed."""
95 if type(x) != type(''): x = repr(x)
96 try:
97 sign, intpart, fraction, expo = extract(x)
98 except NotANumber:
99 return x
100 intpart, fraction = unexpo(intpart, fraction, expo)
101 intpart, fraction = roundfrac(intpart, fraction, digs)
102 while intpart and intpart[0] == '0': intpart = intpart[1:]
103 if intpart == '': intpart = '0'
104 if digs > 0: return sign + intpart + '.' + fraction
105 else: return sign + intpart
106
107 def sci(x, digs):
108 """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
109 and exactly one digit before.
110 If digs is <= 0, one digit is kept and the point is suppressed."""
111 if type(x) != type(''): x = repr(x)
112 sign, intpart, fraction, expo = extract(x)
113 if not intpart:
114 while fraction and fraction[0] == '0':
115 fraction = fraction[1:]
116 expo = expo - 1
117 if fraction:
118 intpart, fraction = fraction[0], fraction[1:]
119 expo = expo - 1
120 else:
121 intpart = '0'
122 else:
123 expo = expo + len(intpart) - 1
124 intpart, fraction = intpart[0], intpart[1:] + fraction
125 digs = max(0, digs)
126 intpart, fraction = roundfrac(intpart, fraction, digs)
127 if len(intpart) > 1:
128 intpart, fraction, expo = \
129 intpart[0], intpart[1:] + fraction[:-1], \
130 expo + len(intpart) - 1
131 s = sign + intpart
132 if digs > 0: s = s + '.' + fraction
133 e = repr(abs(expo))
134 e = '0'*(3-len(e)) + e
135 if expo < 0: e = '-' + e
136 else: e = '+' + e
137 return s + 'e' + e
138
139 def test():
140 """Interactive test run."""
141 try:
142 while 1:
143 x, digs = input('Enter (x, digs): ')
144 print x, fix(x, digs), sci(x, digs)
145 except (EOFError, KeyboardInterrupt):
146 pass