Re: [問題] 請教高手關於數字的誤差已回收

看板MATLAB作者 (Without Charge)時間16年前 (2009/02/12 07:42), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《pow (體脂肪35%)》之銘言: : 我在我的Matlab 7.4.0(R2007a)裡面輸入 : ans = : 0 : 可是我輸入 : ans = : 5.5511e-017 : 我以為跟原本數字的小數點位數有關係 : 可是當我輸入 : 0.025+0.025+0.025+0.025+0.025+0.025+0.025+0.025+0.025+0.025+0.025+0.025 : +0.025+0.025+0.025+0.025+0.025+0.025+0.025+0.025-0.5 : ans = : 1.1102e-016 : 請問有哪位前輩可以解釋一下 : 為什麼呢? : 要如何讓他只顯示正確的答案:0呢? 1-0.2-0.2-0.2-0.2-0.2 也是一樣 在經過 google 一下後我找了三個網站, 有兩個是 Matlab 的員工 http://blogs.mathworks.com/loren/2006/08/23/a-glimpse-into-floating-point-accuracy/ 這個 Loren 有回一段 "有意思" hugh replied on July 8th, 2008 at 13:55 UTC : matlab must be doing some pretty strange stuff internally for the following: 0.1+0.2-0.3 = 5.551115123125783e-017 My question is why have the matlab dev team not sorted this out in 2008! Mathematica, Java, C# and C++ do not suffer such FP errors for such simple operations (with more complex operations then a certain degree of error is perhaps acceptable?) - Matlab seems to be alone in still have these really basic errors. Matlab dev team care to comment? Loren replied on July 8th, 2008 at 14:50 UTC : Hugh- This is not an error. If MATLAB were built to get that answer to be 0, we’d have to do a bunch of operations to sort the data in the “right” order. How would MATLAB actually know that IS the way the values should be accumulated from the real-world? You can have MATLAB perform calculations in whatever order you wish by using parentheses. Or introduce a function that sorts the data appropriately and then does the sums and differences. As long as there is no way to perfectly represent some values, floating point calculations are subject to round-off error. As for the other languages, it depends on how the code is written so they get exactly 0. If the constants are built into the program rather than user-supplied at run-time, it’s possible that a C++ compiler will reorder the operations on constants. And Mathematica might be doing the calculations using extended precision (but I don’t know that for certain). –Loren = 簡單的說就是 Hugh 問說為什麼 Matlab 到了 2008 年了, 這個簡單的小誤 差還解決不了? Loren 就說這不是 error, 如果真的要讓答案變 0 的話, 我們要作很多事耶~ http://blogs.mathworks.com/desktop/2009/01/12/how-to-be-top-mathematician/ 這個 Ken and Mike 有針對這個問題作清楚的說明, 但還是沒解決 format hex 0.1 + 0.1 + 0.1 0.3 ans = 3fd3333333333334 ans = 3fd3333333333333 在十六進位下, 就是有這麼一個位數不相等呀~ http://www.scribd.com/doc/7343704/MATLAB-Programming-David-Kuncicky 這個電子書裡面有提到另一個例子 1-0.2-0.2-0.2-0.2-0.2 = -5.551115123125783e-017 所以要是有人要用 if 判斷式的話, 要小心 ( 0.3 == 0.1*3) 是 0 喔 --  ╔╯═╗  ╦╦╦ ╬╬╯ ╰╦ ╬ ╬╬╗ ╦╰╬═  ╠╬═ ══   ╔══╗ ╔╬╬╗ ╬ ╩ ║ ╬>║< ╬═ ╔╗╔╗ ∕╚﹨﹨ ╠═ ╠═ ║ ╔╬╗ ╚╯ ╩ ╝  ╩═ ╚╝║╯   ╠═╗ ╚═╗╚══╝ ╠╬║    ╬╬║ ═╬ ╬ 國家研究院AcademyEarthAstroEcophilia環境板 ╯ 。 ╯ ╩╯ m3m3ρ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 142.244.32.84
文章代碼(AID): #19as9IDj (MATLAB)
文章代碼(AID): #19as9IDj (MATLAB)