我将这个问题标记为 javascript,因为即使我目前是用 Python 编写的,如果用 Javascript 更容易实现,我也可以轻松地在 Javascript 中实现它。
我的任务是为化学系做一个有效数字计算检查器。这意味着学生将他们的数据输入到字段中,Web 应用程序将在他们的字段上执行预定义的操作并跟踪有效数字并查看他们的答案是否具有正确数量的有效数字。
当我将问题分解为我认为是一个很好的工作流程时,我意识到我需要一种方法用于 Python(后端,因为这是一个用 Django 制作的网络应用程序)或 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
Run Code Online (Sandbox Code Playgroud)
然后没有 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
Run Code Online (Sandbox Code Playgroud)
所以简单地说,我的问题是我需要一种简单的方法来计算学生没有明确声明的 sigfigs(也就是当它是科学记数法时)。有什么简单的方法可以让我在“e”之前删除每个零,直到它到达第一个非零数字。我想,我需要从拆分字符串的后面开始并删除零直到它变成非零数字?
编辑:所以在稍微摆弄之后,我希望这是解决问题的合适方法。我测试了几次,但不是太严格(也可能有效,但谁知道呢!我不太擅长 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))
Run Code Online (Sandbox Code Playgroud)
我认为正则表达式在这里有点矫枉过正,但你的方法应该有效,而且我确信这不是性能问题。
我认为您最后所描述的内容是正确的。我会使用split('e')后跟rstrip('0'),这将删除“尾随零”。如果您想保留递归调用,则可以将字符串重新组合在一起。
| 归档时间: |
|
| 查看次数: |
3501 次 |
| 最近记录: |