为什么我看到在ECMAScript中/ ActionScript 3的不精确浮点运算的结果吗?浮点、结果、不精确、我看到

由网友(範二姑娘不傷感)分享简介:嘿,让我们直接跳转到一个code示例来说明如何的ECMAScript / JavaScript的/ AS3不能做简单的数学向右(AS3采用了IEEE-754双precision浮点数对于按理说它是相同的,在JavaScript中使用的数量级)Hey all, let's jump straight to a code...

嘿,让我们直接跳转到一个code示例来说明如何的ECMAScript / JavaScript的/ AS3不能做简单的数学向右(AS3采用了IEEE-754双precision浮点数对于按理说它是相同的,在JavaScript中使用的数量级)

Hey all, let's jump straight to a code sample to show how ECMAScript/JavaScript/AS3 can't do simple math right (AS3 uses a 'IEEE-754 double-precision floating-point number' for the Number class which is supposedly identical to that used in JavaScript)...

trace(1.1);         //'1.1': Ok, fine, looks good.
trace(1.1*100);     //'110.00000000000001': What!?
trace((1.1*100)/100);  //'1.1': Brings it back to 1.1 (since we're apparently multiplying by *approximately* 100 and then dividing by the same *approximate* '100' amount)
trace(1.1*100-110); //'1.4210854715202004e-14': Proof that according to AS3, 1.1*100!=110 (i.e. this isn't just a bug in Number.toString())
trace(1.1*100==110);   //'false': Even further proof that according to AS3, 1.1*100!=110

怎么办?

推荐答案

欢迎来到奇妙世界的浮点运算精度。在一般情况下,浮点计算会给你一点效果都非常非常接近正确的,但比较输出为绝对平等是不可能给你结果你期望在不使用四舍五入功能。

Welcome to the wonderful world of floating point calculation accuracy. In general, floating point calculations will give you results that are very very nearly correct, but comparing outputs for absolute equality is unlikely to give you results you expect without the use of rounding functions.

阅读全文

相关推荐

最新文章