Skip to main content
Inspiring
May 19, 2006
Question

Flash can't add :)

  • May 19, 2006
  • 2 replies
  • 148 views
What the hell is going on here:

The script below just adds 0.2 to a variable, and traces that variable...
From 22.8 and on, problems start to occur!

a = 0;
function bla() {
for (i=0; i<120; i++) {
a = a+0.2;
trace(i+": "+a);
}
}
bla();

Trace result:
108: 21.8
109: 22
110: 22.2
111: 22.4
112: 22.6
113: 22.7999999999999
114: 22.9999999999999
115: 23.1999999999999
116: 23.3999999999999
117: 23.5999999999999
118: 23.7999999999999
119: 23.9999999999999

Anyone???


This topic has been closed for replies.

2 replies

Inspiring
May 19, 2006
Inspiring
May 19, 2006
Eric,

> What the hell is going on here:

Before we continue, it's very important you realize that what you've
discovered isn't a Flash problem. Repeat, this is not a Flash problem.
Flash adds just fine.

> The script below just adds 0.2 to a variable, and traces
> that variable... From 22.8 and on, problems start to occur!

What you're seeing is a problem inherent in the way floating point
numbers are represented in binary. This sort of thing occurs in Java, C#,
JavaScript, you name it. In fact, give the following a test.

<script type="text/javascript">
a = 0;
function bla() {
for (i=0; i<120; i++) {
a = a+0.2;
document.write(i + ": "+ a + "<br />");
}
}
bla();
</script>

Type that into a fresh HTML page and test it in any browser you please.
You'll see the same kind of discrepancy.

See Wikipedia for details:

http://en.wikipedia.org/wiki/Floating_point


David
stiller (at) quip (dot) net
Dev essays: http://www.quip.net/blog/
"Luck is the residue of good design."