Skip to main content
 首页 » 编程设计

python math.log 在较大的 int 下输出不准确

2025年05月04日17sky-heaven

这是我的代码,我正在尝试使用 math.log 来查找 int 的日志。 我尝试了大部分方法来解决不准确的日志,但我的代码似乎没有任何效果:

num = 810333333333333333253432343224234 
print(num) 
getcontext().prec = 100 # set the precision  (no. of digits) 
getcontext().rounding = ROUND_DOWN  # this will effectively truncate 
logA = Decimal(math.log(num,2)) 
 
print(logA) 
#find num using component of logs 
seedfrac = Decimal(logA - int(logA)) 
nonfrac = 2**int(logA) 
frac = Decimal(2**seedfrac) 
print(Decimal(frac*nonfrac)) 
#find num directly  
print(Decimal(2**logA )) 

检查值的输出:

810333333333333333253432343224234 
109.320214523928456173962331376969814300537109375 
810333333333340688230991571062453.5576735355138989553226940926052307835750320132600744995177525695124 
810333333333340688230991571062453.5576735355138989553226940926052307835750320132600744995177525695128 

如果您知道任何解决方法,请回复,谢谢。

请您参考如下方法:

math.log 仅适用于 float ,因此当您执行 Decimal(math.log(num,2)) 时,您只是在结果上调用 Decimal将 num 转换为 float ,然后获取其浮点精度日志。

首先将您的数字转换为 Decimal 实例,保留精度,然后使用其对数方法之一(为了便于阅读,在下面插入换行符):

In [22]: Decimal(num) 
Out[22]: Decimal('810333333333333333253432343224234') 
 
In [23]: Decimal(num).ln() 
Out[23]: Decimal('75.77499847546938418941086142055648421904630259496362044 
                  157156139031463040418047508186428539214239394') 
 
In [24]: Decimal(num).ln().exp() 
Out[24]: Decimal('810333333333333333253432343224234.0000000000000000000000 
                  000000000000000000000000000000000000000000020') 
 
In [25]: Decimal(num).ln() / Decimal(2).ln() 
Out[25]: Decimal('109.32021452392844307936383214097698765413874994582696830 
                  23528366628242511675596034347551786781907708') 
 
In [26]: 2**(Decimal(num).ln() / Decimal(2).ln()) 
Out[26]: Decimal('810333333333333333253432343224233.999999999999999999999 
                  9999999999999999999999999999999999999999999548')