quarta-feira, 23 de junho de 2010

Let's calculate

Everyone knows that float point numbers are far from been precise. In fact they are as precise as any other number, the problem is that they work in a different base (2 instead of 10).

Let's take an example to illustrate that: the number 0.01, it is a quite simple and clear number in base 10 notation. Now let's add to it 0.09, which is the expected result? 0.1 right? Well doing it using floating point numbers we will get: 0.09999999999999999.

But why? We it is because altough 0.01 and 0.09 can be easily represented in a base 10 notation it doesn't have a real representation in the base 2 notation. It is something like 1/3 it is 0.3333334, the same with those number. What we have at the end is a periodic number, which is rounded to provided the expected number, but when we do a calculation this number cannot be rounded anymore.

Basic stuff, and I guess everyone faced it before, expecting the right result is the same of someone (yes it is a true story) that wants to divide the 100% by 3 and sum it back and expect to have 100%. Well it is not going to happen, 100% by 3 is 33,333333% and it sum back is 99,99999999%.

Sure that there is nice ways to work around this problem, in most of the languages. But all this introduction is to say about this ways, it is just to present a really nice calculation component/program that you can use in your Java programs: Frink.

"Frink is a practical calculating tool and programming language designed to make physical calculations simple, to help ensure that answers come out right, and to make a tool that's really useful in the real world. It tracks units of measure (feet, meters, kilograms, watts, etc.) through all calculations, allowing you to mix units of measure transparently, and helps you easily verify that your answers make sense. It also contains a large data file of physical quantities, freeing you from having to look them up, and freeing you to make effortless calculations without getting bogged down in the mechanics."
You can use it to calculation with the right precision your nice mathematical stuffs (no more error in 0.01 + 0.09), but you can do even more with that. You can virtually convert any unit to any unit.
The possible calculations goes from the normal phisical stuffs like, energy to temperature to crazy examples like how much time Superman should recharge his energies at the Sun to save Lois Lane and some kids, or even further how much weight Lois should loose to help Superman saving some kids (check the examples here).

Take a look at the main website, it worths and can be really helpfull for you, when you need to do some nice calculation in your application.

And finally for those that want to go further in floating point theory: What Every Computer Scientist Should Know About Floating-Point Arithmetic.


A good sidekick for this post is The Magic Numbers - Forever Lost.

Enjoy it ;-)

Nenhum comentário: