PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Python/system/fpformat.py

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