python - gmpy2 : How do I track precision of mpc operations?

标签 python math precision gmp

假设我有两个 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 对象的精度,特别是在添加和减去它们时?

最佳答案

以下函数将返回两个 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

我还没有广泛测试此功能,但它应该可以让您开始。您需要分别检查实部和虚部。您可能需要修改它以检查符号以及是否执行加法或减法。

关于python - gmpy2 : How do I track precision of mpc operations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11708729/

相关文章:

python - 单独的输入和打印线程?

python - 使用 Numpy 进行矩阵的最小二乘回归

java - 安全整数中值公式

floating-point - 为什么 float 不正确?

python - 检查 RDD 中是否存在值

java - java中的长二进制字符串算术

c# - 在什么情况下我会将操作指定为未选中?

c++ - C++ 中 float、double 或 long double 的精度是什么意思?

c++ - 终止小数

python - 为什么我的阿特金筛法忽略了接近指定限制的数字?