Python 裡使用超過 Double Precision 的運算

Hacker News 上爬到的,是一篇 2019 的文章:「When Double Precision Is Not Enough (」,原文在「T>T: When Double Precision is Not Enough」。

作者是拿矩陣 (matrix) 的運算當例子,遇到了 double precision 造成的計算誤差問題:

There is no error with the program; this discrepancy is caused by a loss of numerical accuracy in the eigenvalue calculation due to the limitation of hardware double precision (16-digit).

解法是用 mpmath 增加精度,算是一種暴力解,到要注意計算會慢很多:

Note that this library is incredibly slow for large matrices, so is best avoided for most applications.

另外在 Hacker News 的討論串裡面看到個有趣的東西:「Herbie: Automatically Improving Floating Point Accuracy」這個專案,你把公式丟進去,Herbie 會試著提供等價公式來維持精度,像是 \sqrt{x+1} - \sqrt{x} = 1 / ( \sqrt{x+1} + \sqrt{x} ) 這種東西。


NASA 的 JPL 回答「你們用的圓周率是 3.14 嗎?」的問題

NASAJPL 回答了他們所使用的圓周率:「How Many Decimals of Pi Do We Really Need?」。


For JPL's highest accuracy calculations, which are for interplanetary navigation, we use 3.141592653589793.

先拿目前離地球最遠的人造物 Voyager 1 來舉例,約 201 億公里 (125 億英里) 的距離,使用這個小數下 15 位的圓周率,與實際的圓周率算出來的誤差只有 3.81 公分 (1.5 英寸):

The most distant spacecraft from Earth is Voyager 1. It is about 12.5 billion miles away.

It turns out that our calculated circumference of the 25 billion mile diameter circle would be wrong by 1.5 inches. Think about that. We have a circle more than 78 billion miles around, and our calculation of that distance would be off by perhaps less than the length of your little finger.

另外還舉了地球與整個宇宙的數字來計算,需要的精確度沒有想像中那麼大 XD