**
Problem:
**

You’re working some math equations with Actionscript and tracing the results when you notice some results are off by a very small value.

output:2 2.1 2.2 2.3 2.4 2.5000000001 2.6 2.7000000001 2.8 2.9 3

**
Solution:
**

This is called afloating point errorand is apparently a normal computing error that affects all aspects of computing, not just flash. You can fix this by running the values through thecorrectFloatingPointErrorfunction I’ve posted below.

I originally found this information/code on a post called Floating-point errors got you down?

I won’t repeat everything I read there, you can check that out yourself. However, I thought I would re-post this information with the heading “Innaccurate math results” because that’s what I had been searching for before I realized I was experiencing a floating point error. Anyway, here’s the code:

/** * Corrects errors caused by floating point math. */ public function correctFloatingPointError(number:Number, precision:int = 5):Number { //default returns (10000 * number) / 10000 //should correct very small floating point errors var correction:Number = Math.pow(10, precision); return Math.round(correction * number) / correction; } /** * Tests if two numbers are <em>almost</em> equal. */ public function fuzzyEquals(number1:Number, number2:Number, precision:int = 5):Boolean { var difference:Number = number1 - number2; var range:Number = Math.pow(10, -precision); //default check: //0.00001 <difference> -0.00001 return difference <range && difference> -range; } /* Copyright (c) 2007 Josh Tynjala Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

Thanks for the help.

jg

Comment by John G — March 16, 2010 @ 6:44 pm

saved some brain ache. Cheers!

Comment by Andy — May 16, 2012 @ 7:32 am