Search code examples
pythonarraysnumpyroundingtrailing

How can I keep trailing zeros in a list or np.array?


I'm performing a little bit of statistics using python, I have this dataset:

test=[0.200,0.220,0.220,0.120,0.330,0.330]

Python automatically convert it in [0.2, 0.22, 0.22, 0.12, 0.33, 0.33] but in fact the zeros are significant figures in my calculation so I would like to keep them in the array. I know that I can import decimal and use Decimal for a single value but how can I keep all trailing zeros in a list or np.array?

Think that you are inserting experimental data using a python script, data are precise until the third figure so I want to keep track that 0.020 means that in the third figure is actually a 0. How can I achieve this task? This is a very important issue for a chemist or an engineer.

I need it because I have to keep track of significant figures for the next calculation... Ideally I have to count the number of significant figure in this case 3 and use it in the next calculation, that is a sort of historgram plotting with the bin width related to the number of significant figures.


Solution

  • The question is a bit inherently flawed, I think. Not only is there no real difference between 0.200 and 0.2, but the computer does not store the data in a decimal format, just binary. (To that end, the computer may store 0.2 as 0.20000000000000000000001 just because of precision issues, but this is not actually possible to truncate at the storage level due to the limitations of binary representation.)

    If you just want the values printed with three significant digits, you can use

    print "%.3f" % float_var
    

    And if you want to round all future calculations to three decimal points, use

    round(float_var,3)
    

    But as far as the actual calculation goes, there's nothing to be gained from it. 0.200 has the same effect on calculations as 0.2 whether you're using Python, C, Java, or a pencil and paper.

    EDIT: If you really need the significant digits, there's no reason you can't use Decimal objects in a list. https://docs.python.org/2/library/decimal.html offers a fairly quick way of converting them en masse from a string:

    data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
    

    Or if you already have an array of floats that you need to bring to three significant digits, you can do this:

    import decimal
    
    def toDecimal(x):  # x is a float.
      return decimal.Decimal(str(x)).quantize(decimal.Decimal('1.000'))
    
    data = map(toDecimal, float_var_list)
    

    As far as counting the number of significant digits goes, I don't think there's a built-in function for that, but playing around with strings will give you an answer without much trouble.

    def numDigits(x):  # x is a Decimal object.
      splitDecimal = str(x).split(".")
      return len(splitDecimal[1])