作者etrexetrex (ETREX)
看板Flash
标题Re: [问题] 想请问flash高手...这程式哪里出问题?
时间Mon Nov 20 09:57:12 2006
※ 引述《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