On significant figures of numbers in python [closed]

断了今生、忘了曾经 提交于 2019-12-11 20:43:40

问题


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 units depending on the study it comes from. Here is an example of what I mean:

[...,105.0,20.0,3.5,4.25,9.78,7.2,7.2] 

These are of course of type:

<type 'numpy.float64'>.

If I print out the last number, for instance:

print list[-1]
>>> 7.2

However, if accessed in this way, I get:

7.2000000000000002

I understand that floats are by default 64 bits, so doing a calculation with them (i.e. - converting this list of measurements) returns a converted value which is 64 bits. Here is an example of the converted values:

[105.27878958,20.0281600192,3.47317185649,4.27596751688,9.82706595042,7.27448290596,7.26291009446]

Accessing them either way (using print or not), returns a 64 bit number. But clearly there is something else going on, otherwise the print function wouldn't really know how to display the true measurement. I would like to report the converted values to the same level of accuracy as the original measurements. Is there a way I can do this in python?


回答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]) 


来源:https://stackoverflow.com/questions/23748623/on-significant-figures-of-numbers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!