Monthly Archives: January 2007

Floating-point errors got you down?

Many developers will never encounter issues when floating-point math fails to return the correct result. Every once in a while, when you’re expecting to see a number like 10.1 in your trace panel, you might actually see 10.1000000001. This isn’t a specific issue with Flash either. By it’s very nature, any sort of calculation with floating-point numbers can result in tiny, nearly insignificant errors anywhere in modern computing.

In many cases, that number could get corrected the next time you use it in a mathematical operation. Other times, you’ll never notice that something went wrong because you might be animating some object, and the position gets rounded off anyway. You won’t always be so lucky, though. At some point in your future, you may need to display a number to the user. Imagine their look of shock as some crazy number with ten decimal places appears on the screen. “Oh my god! Why is it doing that?” exclaims a user of your cool new Flex app.

It gets worse. When these errors occur, checking if two numbers are equal can fail as well. Now, when you need to know if your function returned a multiple of two, and you get 15.9999999999, bad things can happen. Another problem, which I’ve run into a few times, is when I’m “counting” between two numbers, like two and three:

2
2.1
2.2
2.3
2.4
2.5000000001
2.6
2.7000000001
2.8
2.9
3

Consider the following two functions. I’ve been using them for a while now, and they work great. The first, correctFloatingPointError will manipulate the number (even a fractional one) with some clever multiplication, division, and rounding to try to account for the error. The second fuzzyEquals will check if two numbers are almost equal. In many cases, if two numbers have a difference of 0.00001, they might as well be considered equal. With both of these functions, you can manipulate the precision to allow for more accurate or inaccurate calculations depending on your needs.


/*
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.
*/

/**
 * 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 almost 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  -0.00001

	return difference  -range;
}

If you have any more tips in this area, I’d like to hear them. Those two functions have been enough for my needs so far, but my toolbox always has room for an extra trick or two.

Check out the speakers at Flex Maniacs

A few minutes ago, I remembered that the list of sessions would be announced for Flex Maniacs today. If you’re not familiar, Flex Maniacs is another great new conference focused on Adobe Flex. Sponsored by Fig Leaf Software and Adobe, it will be taking place in Washington DC on June 25-26, 2007. If you can’t make it to 360 Flex because tickets sold out too fast, be sure to keep your budget open for Flex Maniacs. It looks to be just as exciting!

The list of sessions includes a plethora of Flex goodness including skinning, component development, Flex Data Services, using other server-side languages with Flex, Cairngorm, memory management, and too many other topics to list them all here. Many sessions will be led by real Adobe employees like Ted Patrick (evangelist extraordinaire). Others will have an industry expert like Chafic Kazoun at the helm. Oh yeah, and I’ll be speaking too.

The lecture I’ll be giving will focus on my open source TreeMap component for Flex 2. Here’s the official description:

Though the Flex 2 SDK ships with an impressive array of useful components, opportunities abound for the creation of more advanced visualizations that add new depth and interactivity to Rich Internet Applications. Treemaps, originally developed by Ben Shneiderman of the University of Maryland, offer an interesting way to display hierarchal data that goes beyond standard Tree components.

The Flex development community is growing quickly, and many developers want a look at the process and design considerations required for the creation of a complex component. Josh Tynjala shares his open source Flex TreeMap component with an in-depth study of its data handling methods, optimization considerations, and points for extensibility.

To be more specific, I plan to talk about using data descriptors with your components to allow custom or complex data structures, to show some of the methods I used to optimize the drawing code for the TreeMap, and a bit on the subject of using fields and functions to allow the user to customize your component without subclassing.

I’m pretty excited because this will be the first time I’ll be speaking at a conference. Thankfully, I have several months to prepare, and I plan to get it down to an art form by the time I’m facing a hundred ravenous Flex developers. All I ask of my audience is that you hold off on throwing rotten vegetables until after the Q&A.

One more thing. It looks like they need a couple more brave folks to do hands-on sessions at the conference. Go submit a topic if you think you’ve got a good one.

Tales of a Switcher: Josh Gets a Mac

Last week, I bought my first Apple Mac. I’ve been a long-time Windows user, and it took me some time to decide on this purchase. In high school, I played a bit with an older Mac at the library, but I never wanted one myself. In college, I remember trying some newer Macs with OSX. At the time, they ran pretty slowly when compared to the blazing fast gaming box I had in my dorm room, and I didn’t like the single-button mouse. It wasn’t until Apple switched to the faster Intel processors, they released of the ultra-small Mac Mini, and I discovered the safety-net known as Parallels that I felt I was ready to buy a Mac.

Certainly, it helps a great deal that I work with Adobe products. Adobe supports applications like Flex Builder, Flash Authoring, and Photoshop on both Windows and OSX. For other applications, especially simple utilities, I’ve had to spend a bit of time searching for proper alternatives. Here’s a list with a few useful (and free!) applications to help ease your switching pains. I’m sure a million other switchers have listed them too, but I felt like sharing.

Witch adds Alt-Tab support to OSX. While Command-Tab offers similar functionality, it doesn’t allow the user to switch between individual windows. Instead, it seems to switch to the most recently used window of each application. Witch has an amazing array of options to customize the look and feel of its functionality, and I highly recommend it.

If you like using Gaim or Trillian for instant messaging on Windows, you’ll want to check out Adium. It has a simple interface that’s very easy to use. I wish I had it on Microsoft side of life.

For FTP access, I’ve started using CyberDuck. While its interface looks nothing like FileZilla, my personal favorite on Windows, I still found it pretty easy to use.

Of course, both Firefox and Thunderbird work on Macs too. If you’re used to using Internet Explorer on Windows, Firefox will probably feel the most familiar. Interestingly enough, both of these programs have different behaviors in some cases when you change between platforms. For instance, I often press the Delete key to move an email to the trash in Thunderbird on Windows, but it doesn’t seem to do anything (other than cause the mouse pointer to disappear for a moment) on the Mac version.

As a Windows user, I commonly use the Home and End keys to move the cursor to the start and end of a line of text. Much to my dismay, these keys behave in a completely different manner on OSX. When I’m coding, I constantly find myself at the beginning or end of the file, rather than the line I was editing. Life Hacker has a good tip for making Home and End behave in a more familiar way. For some reason, I couldn’t get that particular solution to work, but I found a link in the comments to a program called DoubleCommand. The user interface leaves much to be desired, but it worked for me.

If you ever miss an episode of your favorite TV show, or you’re into downloading Linux ISOs, you may want to check out Transmission, a BitTorrent client. I’m a big fan of uTorrent on Windows, which has loads of options, but I’ve been pleasantly surprised at how much I like Transmission for its simplicity. I guess that’s the Mac Way™.

As I continue to explore and discover new things, I’m sure I’ll share more of my adventures as a Mac switcher. I doubt I’ll be making any big rants about how I miss Windows, though, because so far it’s been smooth-sailing.

Silvafug Meeting for January 2007

Work with Flex in the Bay Area? You may be interested in dropping by the Silicon Valley Flex User Group meeting tomorrow, January 11, 2007. The night is divided into two parts. First, from 5:00 – 7:00pm, they’ll be offering free Flex training. The topics for the month are web services and events. This will be the third of six separate classes. Don’t worry if you can’t make it. This series of classes will run again in the future.

The main Silvafug meeting starts at 7:30pm. If you’re not interested in the training, feel free to drop by for the meeting because Mark Piller, founder and CEO of Midnight Coders, will be visiting. He’ll be speaking about Remoting and AMF outside of the Java server environment. Expect some good information on WebORB for .NET, Ruby, and PHP.

The meeting takes place at eBay Townhall in San Jose, CA. You can get directions to the meeting on Yahoo! Maps. For more information, please visit the Silvafug website, and be sure to check out the mailing list for future announcements.

I hope to see you there!

Enhancement to ActionScript 3 SHA-1 class

Update: My changes have been accepted to corelib. Please download the official release.

Recently, I worked on a project that required me to use the SHA1 class from Adobe’s open source corelib for ActionScript 3. Unfortunately, the currently available class can only create a hash for string data. That’s cool, but limiting. With some surprisingly simple tweaks, I updated the class to work with raw ByteArray data. Now, we’re talking cool, and infinitely more useful!

//a simple string to hash with the original functionality
var message:String = "The quick red dog jumped over the lazy fox.";

trace(SHA1.hash(message));
//output: 8aa9f4a49d457eb847cb1a2e4f67a4113cdb8bdf

//write the same string to a ByteArray
var rawMessage:ByteArray = new ByteArray();
rawMessage.writeUTFBytes(message);

trace(SHA1.hashBytes(rawMessage));
//output: 8aa9f4a49d457eb847cb1a2e4f67a4113cdb8bdf (it's the same!)

If you haven’t heard, Mike Chambers arecently announced the release of Adobe’s open source ActionScript 3 libraries on Google Code. They’re hoping that this will help encourage more involvement from the developer community. I talked to Mike a while ago about my enhancements, and I’m hoping to get them integrated soon. For now, I wanted to get these changes in people’s hands. You can download the updated code here and use it under the same license terms as the original version.

I had the weirdest dream last night

One morning, I wake up and head over to the computer to check my email. I turn on the monitor, and I discover that my girlfriend has left a browser window open from the night before. Curiously, I take a look at the open webpages, and I find several blog postings and even a couple of webcomics. Strangely enough, they’re all about me.

Photoshop palette with 'Josh Tynjala' as a color name

Let’s rewind for a second. A couple months beforehand, in my dream world, Adobe announced a contest. They wanted to replace the default color palette in Photoshop, so they asked the community to submit their favorite colors. The winners would have their colors included in the default palette, and they’d get some random prize, like a Wii or something of that nature. Amused, I submitted a color and forgot about it.

In one of open blog postings, an Adobe staffer announces a huge list of the finalists with their colors. He asks his readers to list their favorites in the comments. As I’m reading through these comments, I keep seeing my name. That’s cool. Obviously, I picked a most excellent shade of green.

Something just doesn’t seem right, though. No one else’s name is listed in anyone’s comments. You see, the rest of the names happen to be names of colors. I quickly scroll back up to the list of finalists. Sure enough, it says “‘Josh Tynjala’ submitted by Josh Tynjala”. Apparently, that fateful day when I submitted my color, I misinterpreted the form. Rather than picking a clever color name like “Gregarious Green”, I thought it was asking for my name. Oops.

As this blog posting with the finalists made its rounds, other people started writing about it. Except the authors didn’t declare their own favorite colors. No, instead they called me a genius. You see, by naming the color after myself, I had figured out a way to get my name into Photoshop. Every day, a million designers would see my name.

That’s how I became a minor Internet celebrity… in my dreams.