patternpythonMinor
Pretty print with unit and physical suffix
Viewed 0 times
suffixprettywithprintphysicalandunit
Problem
I have a solution for pretty printing physical values with the correct suffix (kilo, mega etc.).
I'd like to discuss my solution with you.
Screen output:
I'd like to discuss my solution with you.
# -*- coding: utf-8 -*-
import math
def eng_format(x, unit=''):
e =(math.floor(math.log10(x))//3)*3
sL = ['f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G']
idx = int(e/3) + sL.index('')
if idx=len(sL):
s = '*10^%d '%e
else:
s = sL[idx]
nx = x * 10**(-e)
return '%.2f%s%s'%(nx, s, unit)
if __name__ == '__main__':
print eng_format(0.002, 'V')
print eng_format(0.000003221, 'A')
print eng_format(30589, 'A')
print eng_format(60000000, 'W')Screen output:
2.00mV
3.22uA
30.59kA
60.00MWSolution
- Use better variable naming, with proper vocabulary. In particular, "significand" is the term to use instead of
nx.
- You multiplied some intermediate result by 3 to obtain
e. Then you immediately doidx = int(e/3) + …, which represents wasted work. More importantly, clarity suffers. I suggest replacingewithpower_of_1000 = int(math.floor(math.log10(x) // 3)), whose intent is much clearer.
- You can take advantage of the fact that negative indexes count backwards from the end of a list.
- There should be a Space in front of each prefix for consistency with the
'*10^%d 'format.
import math
def eng_format(x, unit=''):
# U+03BC is Greek lowercase mu
UNITS = [' ', ' k', ' M', ' G'] + \
([None] * 10) + \
[' f', ' p', ' n', u' \u03bc', ' m']
power_of_1000 = int(math.floor(math.log10(x) // 3))
exponent = 3 * power_of_1000
prefix = UNITS[power_of_1000]
if prefix is None:
prefix = '*10^%d ' % exponent
significand = x * 10**(-exponent)
return '%.2f%s%s' % (significand, prefix, unit)
Context
StackExchange Code Review Q#50945, answer score: 5
Revisions (0)
No revisions yet.