只是爲了好玩,因爲它非常簡單,我寫了一個簡短的程序來生成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