Re: [問題] 想請問flash高手...這程式哪裡出問題?
※ 引述《jonathanmeow (喵)》之銘言:
: 為了證實我的想法
: 我用下列程式測試
: 隨機取出兩個數字後
: 將其中一個除以10另外一個除以100
: 然後再將兩個都乘以100
: 接著判斷這兩個數字和她們四捨五入到整數位的數字是否相等
: 若不相等 列出結果出來
: 程式如下
: **********************************************
: _root.onEnterFrame=function () {
: t1=Math.floor(Math.random()*31)+1;
: t2=Math.floor(Math.random()*31)+1;
: t1=t1/10;
: t2=t2/100;
: t1=t1*100;
: t2=t2*100;
: if(t1!=Math.round(t1)){
: trace(t1);
: trace(Math.round(t1));
: trace(t1+"!="+Math.round(t1));
: }
: if(t2!=Math.round(t2)){
: trace(t2);
: trace(Math.round(t2));
: trace(t2+"!="+Math.round(t2));
: }
: }
: function gcd(int1,int2) {
: a=Math.max(int1,int2);
: b=Math.min(int1,int2);
: while(a%b!=0){
: c=a-Math.floor(a/b)*b;
: a=b;
: b=c;
: }
: return b;
: }
: ******************************************
: 結果trace出來的結果
: 會有
: 110
: 110
: 110!=110
: 的狀況
: 110不等於110 ????
: 這真是太奇妙了
這是浮點數儲存時會造成的問題
因為浮點數用二進位表示法去逼近十進位的值
例如0.5 = 1/2 可以用2進位完全的表示
但 0.4 = 0.25 + 0.125 + 0.015625 + .....
二進位是無法表示0.4的
但是可以逼近到 0.3999999
因此若將實驗改為
隨機取出兩個數字後
將其中一個除以16另外一個除以128
然後再將兩個都乘以128
接著判斷這兩個數字和她們四捨五入到整數位的數字是否相等
應該就不會出現數字失真的問題
--
無名網誌:http://www.wretch.cc/blog/et284vu065k3
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.228.133.157
討論串 (同標題文章)
Flash 近期熱門文章
PTT數位生活區 即時熱門文章