Python计算有效数字 [英] Python counting significant digits

查看:346
本文介绍了Python计算有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将此问题标记为javascript,因为即使我目前在Python中编写此内容,如果在Javascript中实现起来更容易,我也可以在Javascript中轻松实现。

I tagged this question as javascript because even though I currently wrote this in Python, if it would be easier to implement in Javascript, I could easily implement it in Javascript.

我的任务是为化学系制作一个重要的数字计算检查器。这意味着学生将他们的数据输入到字段中,网络应用程序将在他们的字段上执行预定义的操作并跟踪重要数字并查看他们的答案是否具有适当数量的有效数字。

My assignment is to make a significant figure calculation checker for the chemistry department . What that means is that the student enters their data into the fields, the web app will perform predefined operations on their fields and keep track of significant figures and see if their answer has the proper number of significant figures.

当我把问题分解为我认为是一个很好的工作流程时,我意识到我需要一种方法来处理Python(后端,因为这是一个用Django制作的Web应用程序)或Javascript (因为你总是可以在前端验证它没问题)来确定有效位数。我做了一点研究,遇到了这个问题,告诉我我需要工作用python字符串而不是浮点数。我当前的python代码感觉几乎完整,但我仍然面临一个主要挑战

When I broke the problem down into what I figure is a good work flow, I realized that I would need a way for either Python (the backend since this is a web app made in Django) or Javascript (cause you could always validate it on the front end no problem) to determine the number of significant digits. I did a little research and came across this question which tells me that I needed to work with python strings instead of floats. My current python code feels ALMOST complete, but there is still one major challenge I face

import re
def find_sigfigs(x):
    # change the 'E' to lower case if the student typed it in as uppercase
    x = x.lower()
    if ('e' in x):
        myStr = x.split('e')
        # this function assumes that the number on the left of the 'e' is
        # the number of sigfigs. That would be true for user input but not
        # true when python converts a float to scientific notation
        return len( (re.search('[0-9]+', myStr[0])).group() )
    else:
        # put it in e format and return the result of that
        ### problem: python makes me hard code the number of sigfigs as '2'
        ### without the 2 there it always defaults to 6
        return find_sigfigs('%.*e' %(2,float(x)))

>>> find_sigfigs('1.3e-4')
>>> 2
>>> find_sigfigs('1234')
>>> 3
>>> find_sigfigs('123456')
>>> 3
>>> find_sigfigs('1.2345e3')
>>> 5

然后没有2

return find_sigfigs('%.e' %(float(x)))

#Because it changes it to 1.234000e3
>>> find_sigfigs('1234')
>>> 7

#Because it changes it to 1.234560e5
>>> find_sigfigs('123456')
>>> 7

简单地说,我的问题是我需要一种简单的方法来计算sigfigs没有明确地由学生宣布(也就是说它是科学记数法)。是否有一些简单的方法,我可以在'e'之前删除每个零,直到它达到第一个非零数字。我想,我需要从拆分字符串的后面开始删除零,直到它变为非零数字?

So simply put, my problem is that I need a simple way to count the sigfigs when it is not explicitly declared by the student (aka when it is in scientific notation). Is there some easy way that I could drop every zero before the 'e' until it gets to the first non zero digit. I guess, I need to start from the back of the split string and remove zeros until it gets to a nonzero digit?

编辑:所以稍微摆弄一下后,我希望这是解决这个问题的合适方法。我测试了好几次,但不是太严格(也就是说它可能有用,但谁知道!我不太擅长sigfigs ......)

So after a little more fiddling, I hope this is an appropriate solution to the problem. I tested it several times, but not too rigorously (aka it probably works but who knows! I'm not too good at sigfigs...)

def find_sigfigs(x):
    '''Returns the number of significant digits in a number. This takes into account
       strings formatted in 1.23e+3 format and even strings such as 123.450'''
    # change all the 'E' to 'e'
    x = x.lower()
    if ('e' in x):
        # return the length of the numbers before the 'e'
        myStr = x.split('e')
        return len( myStr[0] ) - 1 # to compenstate for the decimal point
    else:
        # put it in e format and return the result of that
        ### NOTE: because of the 8 below, it may do crazy things when it parses 9 sigfigs
        n = ('%.*e' %(8, float(x))).split('e')
        # remove and count the number of removed user added zeroes. (these are sig figs)
        if '.' in x:
            s = x.replace('.', '')
            #number of zeroes to add back in
            l = len(s) - len(s.rstrip('0'))
            #strip off the python added zeroes and add back in the ones the user added
            n[0] = n[0].rstrip('0') + ''.join(['0' for num in xrange(l)])
        else:
            #the user had no trailing zeroes so just strip them all
            n[0] = n[0].rstrip('0')
        #pass it back to the beginning to be parsed
    return find_sigfigs('e'.join(n))


推荐答案

我认为正则表达式在这方面有点过分,但你的方法应该是工作,我相信这不是性能问题。

I think regular expressions are a bit of an overkill here, but your method should work and I'm sure it's not a performance issue.

我认为你跟你最后描述的一样正确。我会使用 split('e'),然后是 rstrip('0'),这将删除'尾随零' 。如果你想保持递归调用,你可以将字符串重新组合在一起。

I think you're on the right track with what you describe at the end. I would use split('e') followed by rstrip('0'), which will remove 'trailing zeros'. You can then put the string back together if you want to keep the recursive call.

这篇关于Python计算有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆