I have a very simple question. I have an array of floats
a = array([0.01,0.1,10,100,1000])
I would like to print this array so that the end result looks something like
10$^-2$, 10$^-1$, ....
Is that possible with the % command?
a = [0.01,0.1,10,100,1000]
for x in a:
base,exp = "{0:.0e}".format(x).split('e')
print "{0}0$^{1}$".format(base,exp)
output:
10$^-02$
10$^-01$
10$^+01$
10$^+02$
10$^+03$
10$^+00$ for 1, but since the OP didn't specify the behavior, that seems fine. May not work for non-10 inputs, but OP didn't specify that behavior either. Maybe there is a very small chance that rounding error will mess things up, perhaps with {.0e}? But I could not trigger it.base,exp = "{0:.0e}".format(x).split('e'), then print "{0}0$^{1}$".format(base,exp)as a one-liner:
["10$^{}$".format(int(math.log10(num))) for num in a]
or more clearly:
from math import *
def toLatex(powerOf10):
exponent = int( log10(powerOf10) )
return "10$^{}$".format(exponent)
nums = [10**-20, 0.01, 0.1, 1, 10, 100, 1000, 10**20]
[(x, toLatex(x)) for x in nums]
[(1e-20, '10$^-20$'),
(0.01, '10$^-2$'),
(0.1, '10$^-1$'),
(1, '10$^0$'),
(10, '10$^1$'),
(100, '10$^2$'),
(1000, '10$^3$'),
(100000000000000000000L, '10$^20$')]
Try this:
for i in str(a):
print i
Output:
0.01
0.1
10.0
100.0
1000.0
If you prefer scientific notation:
for i in str(a):
print '%.3e' % i
Output:
1.000e-02
1.000e-01
1.000e+01
1.000e+02
1.000e+03
The digit in '%.3e' controls the number of digits to the right of the decimal point.
EDIT: if you want to print everything on the same line, add a comma ',' at the end of each print statement.
1, as well as for floats which are not powers of 10.