只是为了好玩,因为它非常简单,我写了一个简短的程序来生成Grafting numbers,但由于浮点精度问题,它没有找到一些较大的例子。Python浮点任意精度可用?
def isGrafting(a):
for i in xrange(1, int(ceil(log10(a))) + 2):
if a == floor((sqrt(a) * 10**(i-1)) % 10**int(ceil(log10(a)))):
return 1
a = 0
while(1):
if (isGrafting(a)):
print "%d %.15f" % (a, sqrt(a))
a += 1
该代码遗漏了至少一个已知嫁接编号。 9999999998 => 99999.99998999999999949999999994999999999374999999912...
它似乎降低了乘以10**5
后额外的精度。
>>> a = 9999999998
>>> sqrt(a)
99999.99999
>>> a == floor((sqrt(a) * 10**(5)) % 10**int(ceil(log10(a))))
False
>>> floor((sqrt(a) * 10**(5)) % 10**int(ceil(log10(a))))
9999999999.0
>>> print "%.15f" % sqrt(a)
99999.999989999996615
>>> print "%.15f" % (sqrt(a) * 10**5)
9999999999.000000000000000
因此,我写了一个简短的C++程序,以查看它是否是我的CPU以某种方式截断了浮点数或python。
#include <cstdio>
#include <cmath>
#include <stdint.h>
int main()
{
uint64_t a = 9999999998;
printf("%ld %.15f %.15f %.15f %.15f\n", a, sqrt((double)a), sqrt((double)a)*1e4, sqrt((double)a)*1e5, sqrt((double)a)*1e6);
a = 999999999998;
printf("%ld %.15f %.15f %.15f %.15f\n", a, sqrt((double)a), sqrt((double)a)*1e5, sqrt((double)a)*1e6, sqrt((double)a)*1e7);
a = 99999999999998;
printf("%ld %.15f %.15f %.15f %.15f\n", a, sqrt((double)a), sqrt((double)a)*1e6, sqrt((double)a)*1e7, sqrt((double)a)*1e8);
return 0;
}
,输出:
9999999998 99999.999989999996615 999999999.899999976158142 9999999999.000000000000000 99999999990.000000000000000
999999999998 999999.999998999992386 99999999999.899993896484375 999999999999.000000000000000 9999999999990.000000000000000
99999999999998 9999999.999999899417162 9999999999999.900390625000000 99999999999999.000000000000000 999999999999990.000000000000000
因此,它看起来像我跑起来难防的浮点精度的极限,因为它认为该CPU被斩去其余位,其余的差异是浮点错误。有没有办法在Python下解决这个问题?或者我需要迁移到C并使用GMP或其他?
可以使用['fractions'模块](https://docs.python.org/3/library/fractions.html)执行有理数的精确算术。 – jfs 2015-09-30 14:55:47