【问题标题】:Decimal Precision in Python [duplicate]Python中的小数精度[重复]
【发布时间】:2018-10-26 05:38:51
【问题描述】:

当我运行代码时

b = 7**7

我得到 b 为 823543

但是当我运行时

b= 823543.0**(1.0/7.0)

它给我 b 为 6.999999999999999

如果它像 4**(1/2) 这样简单,则返回 2。

我的问题是为什么 python 不只返回一个完美的 7?

我也这样做是为了检查一个数字是否可以写成 n 可以写成 p^q 的形式,其中 p>0 和 q>1 这样做我这样做了:

 def isPower(self, A):
    possible = 0 # Integer value to check  if it is possible , 0 assuming it is false initally
    if(A==1):
        return 1
    for i in xrange(2,A-1):
        res = float(A)**(1.0/float(i)) #Check if it has sqaure root or cube root up untill A-1
        if(res.is_integer()): #If taking the power gives me whole number then saying it is possible
            possible = 1
            break
    return possible

此逻辑因 823543 等更高的数字而失败,因为电源返回的值不精确我将如何解决这个问题?

【问题讨论】:

    标签: python


    【解决方案1】:

    您没有使用小数 - 您使用的是浮点数。他们以准确性换取速度。

    试试这个;

    from decimal import Decimal
    b = 7 ** 7  # 823543
    a = Decimal(1) / Decimal(7)
    b ** a  # returns (for me) Decimal('7.000000000000000000000000004')
    

    【讨论】:

    • OP 想要 7 作为一个完整的号码。
    • @U9-Forward 他们确实如此。这与使用 stdlib python 一样接近。
    • 这有点解释了,所以浮点数的精度有一个上限,而 Decimal 进一步增加了它。希望有办法让我获得完美的 7。
    【解决方案2】:

    为什么不rounding:

    >>> b= 823543**(1/7)
    >>> round(b)
    7
    >>> 
    

    现在你有7(七)

    【讨论】:

    • 是的问题是我现在正在检查一个数字是否可以用 p^q 表示表示为浮点数。四舍五入总是会得到一个完美的整数。
    • @SamThomas float(round(b)) for 7.0
    • 是的,这会起作用,但是当我检查 5 是否可以表示为 p^q 时,5^(1/2) 是十进制答案,如果我将它四舍五入,那么我的程序将假设它可以表示作为 p^q 所以这就是为什么我不能舍入它。
    • @SamThomas 好的,那就不要使用我的 :-)
    【解决方案3】:

    您应该阅读What Every Computer Scientist Should Know About Floating-Point Arithmetic

    简而言之:浮点数表示为尾数和指数。类似的东西

    0.1234 * 10^1
    

    1234 是尾数(如果我没记错的话,指数用 2 补码表示)

    这意味着一些整数不能准确地表示为浮点数。

    您可以将 7 和 823543 完全表示为浮点数,但我认为这不适用于 1/7(手头没有纸):https://www.h-schmidt.net/FloatConverter/IEEE754.html

    另外,请考虑如何计算 n 根。

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多