Cancellation Error

Oct 2 2008

python

今天聽莊永裕教授的 Digital Image Synthesis 課時,聽到一個 Cancellation Error 的東西,是個與 IEEE floating point 有關的「數值計算問題」。

投影片上如是說:

Cancellation error: devastating loss of precision when small numbers are computed from large numbers by addition or subtraction.

寫了個簡單的 c 程式親身試驗一下。

void main(){
        double x1 = 10.000000000000004;
        double x2 = 10.000000000000000;
        double y1 = 10.00000000000004;
        double y2 = 10.00000000000000;

        double z = (y1-y2)/(x1-x2);
        printf("%f\n", z);
}
// output:
// # 11.500000

接著我在想,Python 會不會有這個問題呢? 結果試了一下…一樣!! 看來 CPython 的 number 這個 type 真的是用 double 實作的 :o

comments powered by Disqus