Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding off small numbers in python

I have a table with numbers such as 5E-7, 10E-4 but the numbers are to several decimal points of precision such as 5.646273838E-7. I know I can use the round function in python to set the precision but since all my numbers vary I want to be able to round each one to say 2 d.p but still keeping the exponents in the answer. So I want 5.646273838E-7 to become 5.64E-7 and 2.38212538E-4 to become 2.38E-4. I was trying to use a method where I could convert my numbers to a string and then work out the string length so for 5.646273838E-7 if the string length is ~ 17, I set the rounding to (17-2)*0.5 and it sort of does the job for my data range. But can anyone suggest a better method?

@user545424: Hey that's a very useful thing to know and does the job well, except that my data is being read off a text file which has strings as well as numbers. The strings are the names of the objects, example: Name Prop_1 Prop_2
object_1 5.343e-10 2.574e-10

I then use the following code to read and display it as a table and save as a latex file numpy.set_printoptions(precision=2)

    out=numpy.loadtxt('data.txt', dtype=str,usecols=(0,1,2,3))


    col=zip(*out)
    tab=Table(col)
    tab.write('table',format='latex')
    print(tab)

Thanks

like image 838
user2869276 Avatar asked May 08 '26 00:05

user2869276


2 Answers

>>> format(0.1234, '.2e')
'1.23e-01'

The format function and the closely related str.format method are what you want here. .2 means "2 digits after the decimal point", and e means scientific notation. There are a lot of options; see the format string syntax specification for more details.

like image 104
user2357112 supports Monica Avatar answered May 10 '26 14:05

user2357112 supports Monica


If you're using a numpy array you can use np.round(). For example:

>>> import numpy as np
>>> a = np.random.rand(4,3)
>>> a
array([[ 0.77600629,  0.76947092,  0.8145481 ],
       [ 0.08514862,  0.67965067,  0.90147548],
       [ 0.88886939,  0.57478246,  0.38501869],
       [ 0.57264822,  0.3376192 ,  0.55660758]])
>>> np.round(a,2)
array([[ 0.78,  0.77,  0.81],
       [ 0.09,  0.68,  0.9 ],
       [ 0.89,  0.57,  0.39],
       [ 0.57,  0.34,  0.56]])

Edit:

If you need to keep a certain number of significant figures and not just round, you can do it with np.set_printoptions():

>>> np.set_printoptions(precision=2)
>>> b = a*1e-10
>>> b
array([[  7.76e-18,   7.69e-18,   8.15e-18],
       [  8.51e-19,   6.80e-18,   9.01e-18],
       [  8.89e-18,   5.75e-18,   3.85e-18],
       [  5.73e-18,   3.38e-18,   5.57e-18]])
like image 43
user545424 Avatar answered May 10 '26 14:05

user545424



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!