Skip to content Skip to sidebar Skip to footer

On Significant Figures Of Numbers In Python

Hi I have a somewhat strange question. I am converting a list of numbers (which represent physical measurements), where each are reported to some specified accuracy in arbitrary un

Solution 1:

You have three problems:

1) How do I determine the number of decimal places in the input?

If your Python code literally says [...,105.0,20.0,3.5,4.25,9.78,7.2,7.2], you're out of luck. You've already lost the information you need.

If, instead, you have the list of numbers as some kind of input string, then you have the info you need. You probably already have code like:

for line in input_file:
    data = [float(x) for x in line.split(',')]

You need to record the number of places to the right of the decimal before converting to float, for example:

for line in input_file:
    places = [len(x.partition('.')[2]) for x in line.split(',')]
    data = [float(x) for x in line.split(',')]

2) How do I store that information?

That's up to you. Sorry, I can't help you with that one without seeing your whole program.

3) How do I format the output to round to that number of decimal places?

Use the % operator or {}-style formatting, like so:

print '%.*f' % (places[i], data[i]) 

Post a Comment for "On Significant Figures Of Numbers In Python"