【问题标题】:gmpy2: How do I track precision of mpc operations?gmpy2:如何跟踪 mpc 操作的精度?
【发布时间】:2012-07-29 11:06:27
【问题描述】:

假设我有两个 gmpy2.mpc 对象 xy 精确到 p 位。当我计算 x+y 时,x 和 y 的某些部分可能会取消,所以我的精度会降低。

例如

from gmpy2 import *

x = mpc('-0.55555')
y = mpc('0.5555500000001')
print(x+y)

即使 xy 精确到 ~15,结果也只能精确到 4 位有效数字。

我认为我需要计算出在进行加法和减法运算时发生了多少位取消,然后将其从xy 的最小精度中去掉。对于乘法和除法,我想我最多只会损失 1 位精度。

所以问题很笼统:我如何跟踪mpc 对象的精度,尤其是在加减它们时?

【问题讨论】:

    标签: python math precision gmp


    【解决方案1】:

    以下函数将返回两个mpfr 对象的匹配位数。

    import gmpy2
    
    def matching_bits(x, y):
        '''Returns the number of bits that match between x and y. The
        sign of x and y are ignored. x and y must be of type mpfr.'''
    
        # Force both values to be positive, and x >= y.
        x = abs(x)
        y = abs(y)
        if x < y:
            x, y = y, x
    
        if not isinstance(x, type(gmpy2.mpfr(0))) or not isinstance(y, type(gmpy2.mpfr(0))):
            raise TypeError("Arguments must be of type 'mpfr'.")
    
        x_bits, x_exp, x_prec = x.digits(2)
        y_bits, y_exp, y_prec = y.digits(2)
    
        # (x_exp - y_exp) is the number of zeros that must be prepended
        # to x to align the mantissas. If that is greater than the precision
        # y, then no bits in common.
        if (x_exp - y_exp) > x_prec:
            return 0
    
        x_bits = "0" * (x_exp - y_exp) + x_bits
    
        count = 0
        while count < min(x_prec, y_prec) and x_bits[count] == y_bits[count]:
            count += 1
        return count
    

    我没有对这个函数进行广泛的测试,但它应该让你开始。您将需要分别检查实部和虚部。您可能需要对其进行修改以检查符号以及您是否正在执行加法与减法。

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 2015-09-20
      • 2012-12-23
      相关资源
      最近更新 更多