I’m attempting to format numbers in scientific notation with exponents of base 10, e.g. write 0.00123 as 1.23×10–3, using python 3.
I found this great function which prints 1.23×10^-3, but how can the caret-exponent be replaced with a superscript?
JavaScript
x
8
1
def sci_notation(number, sig_fig=2):
2
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
3
a,b = ret_string.split("e")
4
b = int(b) # removed leading "+" and strips leading zeros too.
5
return a + "x10^" + str(b)
6
7
print(sci_notation(0.001234, sig_fig=2)) # Outputs 1.23x10^-3
8
The function is modified from https://stackoverflow.com/a/29261252/8542513.
I’ve attempted to incorporate the answer from https://stackoverflow.com/a/8651690/8542513 to format the superscript, but I’m not sure how sympy works with variables:
JavaScript
1
15
15
1
from sympy import pretty_print as pp, latex
2
from sympy.abc import a, b, n
3
4
def sci_notation(number, sig_fig=2):
5
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
6
a,b = ret_string.split("e")
7
b = int(b) #removed leading "+" and strips leading zeros too.
8
b = str(b)
9
expr = a + "x10"**b #Here's my problem
10
pp(expr) # default
11
pp(expr, use_unicode=True)
12
return latex(expr)
13
14
print(latex(sci_notation(0.001234, sig_fig=2)))
15
This returns: TypeError: unsupported operand type(s) for ** or pow(): ‘str’ and ‘int’
Advertisement
Answer
Here’s a simple solution:
JavaScript
1
9
1
def SuperScriptinate(number):
2
return number.replace('0','⁰').replace('1','¹').replace('2','²').replace('3','³').replace('4','⁴').replace('5','⁵').replace('6','⁶').replace('7','⁷').replace('8','⁸').replace('9','⁹').replace('-','⁻')
3
4
def sci_notation(number, sig_fig=2):
5
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
6
a,b = ret_string.split("e")
7
b = int(b) # removed leading "+" and strips leading zeros too.
8
return a + "x10^" + SuperScriptinate(str(b))
9