【问题标题】:Quickest way to check if a number has a decimal or not [duplicate]检查数字是否有小数的最快方法[重复]
【发布时间】:2021-04-27 21:09:58
【问题描述】:

我正在输入检查数字是正数、负数以及是否有小数的代码。有没有更快的方法来检查小数?

n = input("Type a number: ")
try:
    n = int(n)
    if n > 0:
        print("n is positive")
    elif n < 0:
        print("n is negative")
    else:
        print("n is zero")
except ValueError:
    n = float(n)
    if n > 0:
        print("n is positive and decimal")
    elif n < 0:
        print("n is negative and decimal")
    else:
        print("n is zero")
print(n)
input()

【问题讨论】:

  • 欢迎来到 SO!为什么需要更快的方法?这里有性能问题吗?
  • 打印(isinstance(num, float)
  • @roganjosh 在输入为"1.2"时失败并进入异常部分
  • (a := float('3.79')) == int(a) 或其他号码怎么样。
  • 是的,我就是这个意思。为了实现@CrazyChucky 和你的建议,最好的工具可能就是正则表达式:)

标签: python


【解决方案1】:

您始终可以使用float,然后检查.is_integer() 方法:

n = float(input("Type a number: "))


if n > 0:
    print("n is positive")
elif n < 0:
    print("n is negative")
else:
    print("n is zero")

if n.is_integer():
    print("n is integral")
else:
    print("n isn't integral")

print(n)
input()

要明确:现在n始终具有float 类型,即使用户输入例如2is_integer 只是告诉你浮点数是否可以表示为整数。

这将停止在浮点数的限制下可靠地工作:

>>> float("12345678901234567.5").is_integer()
True
>>> float("1"+ "0"*309).is_integer()
False

【讨论】:

  • IINM,这通常不能正常工作(尤其是对于大输入):确实,Python3 floats rely on IEEE-754 double-precision(即有限精度),而Python3 integers have unlimited precision
  • @ErikMD 正确。不过,输入必须非常大(>300 位)才有意义。
  • 是的,机器人不一定有 300 多位数字!你可能会得到一个错误的答案,只有 18 位数字:试试float("12345678901234567.5").is_integer()
  • 哦,我反其道而行之(“整数何时不再是整数?”)。这确实是一个可以在正常用户输入上合理发生的缺陷:/ 编辑了答案。
【解决方案2】:

假设您正在寻找专门的“小数”而不仅仅是浮点数,您可以使用这个由floor 函数制作的学校教授算法。

>>> import math
>>> def is_int(x):
...     y=math.floor(x)+math.floor(-x)
...     if y==0:
...             print("It's an integer")
...     if y==-1:
...             print("It's a decimal")
...
>>> is_int(1)
It's an integer
>>> is_int(1.3)
It's a decimal

【讨论】:

    【解决方案3】:

    这是另一个使用% 运算符的版本。

    n = float(input("Enter a number: "))
    
    if n>=0:
        if n > 0 :
            print("Positive Number")
         else:
            print("Zero")
    else:
        print("Negative Number")
    
    if n%1!=0:
       print("Decimal Number")
    else:
       print("Integer")
    

    【讨论】:

      【解决方案4】:

      跟进cmets(12):OP的问题中提出的代码很好。

      但是,如果我们想避免将字符串转换为数字类型和使用异常的成本,也可以依靠正则表达式来直接断言符号和所提供文字的种类。

      例如,通过编写如下内容:

      #!/usr/bin/env python3
      import re
      
      def process(txt):
      
          pat = re.compile(r'^(-)?[0-9]+(\.[0-9]+)?$')
      
          grep = pat.match(txt)
      
          print(txt, 'is:')
      
          if grep is None:
              print('not a numeric string')
          else:
              if grep.group(1) is None:
                  print('some ', end='')
              else:
                  print('some negative ', end='')
              if grep.group(2) is None:
                  print('integer')
              else:
                  print('decimal')
      
      process('-12')
      process('-12.5')
      process('12')
      process('12.5')
      process('foo')
      process(500*'9')
      process(str(input("Type a number: ")))
      

      【讨论】:

      • 要小心。描述float()/int() 接受的字符串的正则表达式比这要复杂一些(例如".1e-3" 是一个有效的浮点数)。
      • @L3viathan 当然:通过稍微更改正则表达式可以很容易地考虑到这一点。实际上我没有提到这一点,因为 OP 的问题只提到了“小数”而不是科学记数法或浮点算术......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2012-02-04
      • 2011-02-05
      • 2013-08-12
      • 2016-08-02
      • 1970-01-01
      相关资源
      最近更新 更多