计算非常大的 x,y 的 (1-1/x)^y 幂

问题描述 投票:0回答:1

我正在考虑在Python中计算非常大的x,y数字$(1-1/x)^y$。 一种方法是使用

exp(y*log1p(-1/x))
,但我不确定它的准确性。

使用这种精度有什么结果吗?例如,限制这样的结果的误差?

我想这比使用近似值更好

exp(-y/x))

python numpy floating-accuracy
1个回答
0
投票

肯定会存在精度问题,尤其是对于非常大的 x 和 y。您可以使用 result = math.expm1(y * math.log1p(-1/x)) 这将为接近零的值计算更高的精度。 另外,就误差范围而言,在不知道 x 和 y 的具体范围的情况下提供一般范围是具有挑战性的。 但是,您可以考虑使用提供专门为高精度设计的函数的数值库,例如Python中的mpmath库。 mpmath 允许您执行任意精度的算术:

from mpmath import mp

mp.dps = 50  # Set the desired precision (adjust as needed)
x=100000000000000000000000000000000000000000000000000000000000000000
y=100000000000000000000000000000000000000000000000000000000000000000
    
result = mp.exp(y * mp.log1p(-1/mp.mpf(x)))

print(result)

#output
Result:0.36787944117144232159552377016146086744581113103177
© www.soinside.com 2019 - 2024. All rights reserved.