Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Python计算有效数字_Javascript_Python - Fatal编程技术网

Javascript Python计算有效数字

Javascript Python计算有效数字,javascript,python,Javascript,Python,我将这个问题标记为javascript,因为尽管我目前是用Python编写的,但如果它更容易用javascript实现,我可以用javascript轻松实现它 我的任务是为化学系做一个有效数字计算检查器。这意味着学生将他们的数据输入字段,web应用程序将对他们的字段执行预定义的操作,并跟踪有效数字,查看他们的答案是否具有正确的有效数字 当我把这个问题分解成我认为是一个好的工作流程时,我意识到我需要一种方法来确定有效位数,无论是Python(后端,因为这是一个用Django制作的web应用程序)还

我将这个问题标记为javascript,因为尽管我目前是用Python编写的,但如果它更容易用javascript实现,我可以用javascript轻松实现它

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

当我把这个问题分解成我认为是一个好的工作流程时,我意识到我需要一种方法来确定有效位数,无论是Python(后端,因为这是一个用Django制作的web应用程序)还是Javascript(因为你总是可以在前端验证它,没有问题)。我做了一些研究,发现这告诉我我需要使用python字符串而不是浮点数。我目前的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

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
简单地说,我的问题是,我需要一种简单的方法来计算学生没有明确声明的符号(也就是科学记数法中的符号)。有没有一种简单的方法,我可以在“e”之前去掉每一个零,直到它到达第一个非零位。我想,我需要从拆分字符串的后面开始,去掉零,直到它变成一个非零的数字

编辑:因此,在进行了一些修改之后,我希望这是解决问题的适当方法。我测试了好几次,但不是太严格(也就是说,它可能可以工作,但谁知道呢!我不太擅长发信号…)


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


我认为你在最后描述的方面是正确的。我将使用
split('e')
,后跟
rstrip('0')
,这将删除“尾随零”。如果希望保留递归调用,则可以将字符串重新组合在一起。

我认为有一种更简单的解决方案不需要递归。此外,上述解决方案仅在传入字符串时有效。对我来说,要求字符串中的有效数字似乎很奇怪,因此感觉函数应该在内部进行转换,或者至少支持传递字符串和数字

以下是我的想法:

def find_sighfigs(编号):
“”“返回数字中的有效位数”“”
#首先将其转换为一个float,以考虑指数中的内容
#表示法,并在平等的基础上获取所有输入。那么SIGIF的数量是多少
#将多余的零剥离到整数左侧后的非零数
#小数位数和小数点的右边
数字=报告(浮动(数字))
令牌=编号。拆分('.'))
整_num=tokens[0].lstrip('0')
如果len(代币)>2:
raise VALUERROR('无效的数字“%s”只允许1位小数“%”(数字))
如果len(令牌)==2:
decimal_num=令牌[1]。rstrip('0')
返回len(整数)+len(小数)
返回长度(整数)

我是否遗漏了一些边缘情况?

感谢您提供了有关
rstrip()
的提示,这让我在正确的轨道上找到了您的解决方案:)请注意
repr()
的使用,因此在Python 2和3中也可以这样做
str()
在Python2和Python3中进行了更改:如果您传入一个类似
1e-5
的数字,这似乎不起作用,因为
str(float(1e-5))
是如何工作的。需要找到一种方法,用适当的零将负指数展开。
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))