Python计算有效数字

2024-03-29 14:05:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我将这个问题标记为javascript,因为即使我目前是用Python编写的,如果用javascript实现更容易,我也可以很容易地用javascript实现它。在

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

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

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

^{pr2}$

简单地说,我的问题是我需要一种简单的方法来计算sigfig,当它不是由学生明确声明的时候(也就是说,当它是科学记数法的时候)。有没有什么简单的方法可以让我把“e”前的每一个0减到第一个非零位数。我想,我需要从拆分字符串的后面开始,去掉零,直到它变成一个非零数字?在

编辑:因此,我希望这是一个适当的解决问题的方法。我测试了几次,但不是太严格(也就是说它可能有用,但谁知道呢!我不太擅长打手势……)

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))

Tags: andoftheto方法innumberreturn
1条回答
网友
1楼 · 发布于 2024-03-29 14:05:08

我认为正则表达式有点过头了,但您的方法应该可以工作,我确信这不是性能问题。在

我想你在结尾描述的是对的。我将使用split('e')后跟rstrip('0'),这将删除“尾随的零”。如果希望保留递归调用,则可以将字符串放回一起。在

相关问题 更多 >