Category Archives: programming

Storing Currency Into Floating Point Type Is Not A Good Idea

Storing currency into a floating-point type seem to be the most intuitive thing to do, especially most major currency are displayed as fraction to the cents, eg: $10.50. However floating-point is designed to store fraction up into specific precision, but currency is only subdivisible until a certain amount. For example the smallest fraction is US Dollar is 1 cent, Australian Dollar 5 cent and so on. Hmm, now it sounded like storing them as integer made much more sense!

Here’s one problem I came accross recently: split a sum of money proportionally into N people. That sounded simple, until I realize if the sum cannot be divided equally, you need to take into account roundings and who get lucky to receive the remainder.

For example: divide $10 into 3 people. Each person will get $31/3.. but the problem is there isn’t any $1/3 in real life (at least in all dollar currencies I know of).

At first.. I thought I can implement the code like this:

double amount = 10.0;

double person_a = amount / 3.0;
double person_b = amount / 3.0;
double person_c = amount / 3.0;

printf("person a: $%.2f\n", person_a); // This prints the double value rounded to 2 digits after decimal
printf("person b: $%.2f\n", person_b);
printf("person c: $%.2f\n", person_c);

But this code gives me

person a: $3.33
person b: $3.33
person c: $3.33

Hey the total is only $9.99 where do the 1 cent go?

Obviously this is a rounding problem. 10.0 / 3.0 gives 3.3333333… (up until the limit of double precision), but when rounded into 3.33, we lost 0.0033333…..

Probably a more appropriate code to solve this problem is as follows:

int amount = 1000; // <-- That is 1000 cents, ie: 10 dollar
int remainder = 1000 % 3;

int person_a = amount / 3;
int person_b = amount / 3;
int person_c = amount / 3;

printf("person a: %.2f\n", person_a / 100.0);
printf("person b: %.2f\n", person_b / 100.0);
printf("person c: %.2f\n", person_c / 100.0);
printf("$%.2f remaining, who's the lucky person?\n", remainder / 100.0);

Which gives:

person a: $3.33
person b: $3.33
person c: $3.33
$0.01 remaining, who's the lucky person?

New Programming Jargons

Source: http://blog.codinghorror.com/new-programming-jargon/

1. Yoda Conditions

Yoda-conditions

Using if(constant == variable) instead of if(variable == constant), like if(4 == foo). Because it’s like saying “if blue is the sky” or “if tall is the man”.

2. Pokémon Exception Handling

Pokemon

For when you just Gotta Catch ‘Em All.

try {
}
catch (Exception ex) {
// Gotcha!
}

3. Egyptian Brackets

Egyptian

You know the style of brackets where the opening brace goes on the end of the current line, e.g. this?

if (a == b) {
printf("hello");
}

We used to refer to this style of brackets as “Egyptian brackets”. Why? Compare the position of the brackets with the hands in the picture. (This style of brackets is used in Kernighan and Ritchie’s book , so it’s known by many as K&R style.)

4. Smug Report

Pathreport-med

A bug submitted by a user who thinks he knows a lot more about the system’s design than he really does. Filled with irrelevant technical details and one or more suggestions (always wrong) about what he thinks is causing the problem and how we should fix it.

Also related to Drug Report (a report so utterly incomprehensible that whoever submitted it must have been smoking crack.), Chug Report (where the submitter is thought to have had one too many), and Shrug Report (a bug report with no error message or repro steps and only a vague description of the problem. Usually contains the phrase “doesn’t work.”)

5. A Duck

Duck-wireframe

A feature added for no other reason than to draw management attention and be removed, thus avoiding unnecessary changes in other aspects of the product.

I don’t know if I actually invented this term or not, but I am certainly not the originator of the story that spawned it.

This started as a piece of Interplay corporate lore. It was well known that producers (a game industry position, roughly equivalent to PMs) had to make a change to everything that was done. The assumption was that subconsciously they felt that if they didn’t, they weren’t adding value.

The artist working on the queen animations for Battle Chess was aware of this tendency, and came up with an innovative solution. He did the animations for the queen the way that he felt would be best, with one addition: he gave the queen a pet duck. He animated this duck through all of the queen’s animations, had it flapping around the corners. He also took great care to make sure that it never overlapped the “actual” animation.

Eventually, it came time for the producer to review the animation set for the queen. The producer sat down and watched all of the animations. When they were done, he turned to the artist and said, “that looks great. Just one thing – get rid of the duck.”

6. Refuctoring

Bottle-smashing

The process of taking a well-designed piece of code and, through a series of small, reversible changes, making it completely unmaintainable by anyone except yourself.

7. Stringly Typed

Cat-string-values

A riff on strongly typed. Used to describe an implementation that needlessly relies on strings when programmer & refactor friendly options are available.

For example:

  • Method parameters that take strings when other more appropriate types should be used.
  • On the occasion that a string is required in a method call (e.g. network service), the string is then passed and used throughout the rest of the call graph without first converting it to a more suitable internal representation (e.g. parse it and create an enum, then you have strong typing throughout the rest of your codebase).
  • Message passing without using typed messages etc.

Excessively stringly typed code is usually a pain to understand and detonates at runtime with errors that the compiler would normally find.

8. Heisenbug

unknown

Heisenbug

A computer bug that disappears or alters its characteristics when an attempt is made to study it. (Wikipedia)

9. Doctype Decoration

Charlie-brown-christmas-tree

When web designers add a doctype declaration but don’t bother to write valid markup.

Now on sale!

10. Jimmy

Jimmy

A generalized name for the clueless/new developer.

Found as we were developing a framework component that required minimal knowledge of how it worked for the other developers. We would always phrase our questions as: “What if Jimmy forgets to update the attribute?”

This led to the term: “Jimmy-proof” when referring to well designed framework code.

11. Higgs-Bugson

Higgs-boson-guy

A hypothetical bug predicted to exist based on a small number of possibly related event log entries and vague anecdotal reports from users, but it is difficult (if not impossible) to reproduce on a dev machine because you don’t really know if it’s there, and if it is there what is causing it. (see Higgs-Boson)

12. Nopping

Statue-napping

I’m writing a scifi novel from the POV of an AI, and their internal language has a lot of programming jargon in it. One of the more generalizable terms is “nopping”, which comes from assembler NOP for no-operation. It’s similar to ‘nap’, but doesn’t imply sleep, just zoning out. “Stanislav sat watching the screensaver and nopped for a while.”

13. Unicorny

Stack-overflow-unicorn

An adjective to describe a feature that’s so early in the planning stages that it might as well be imaginary. We cribbed this one from Yehuda Katz, who used it in his closing keynote at last year’s Windy City Rails to describe some of Rails’ upcoming features.

14. Baklava Code

Baklava

Code with too many layers.

Baklava is a delicious pastry made with many paper-thin layers of phyllo dough. While thin layers are fine for a pastry, thin software layers don’t add much value, especially when you have many such layers piled on each other. Each layer has to be pushed onto your mental stack as you dive into the code. Furthermore, the layers of phyllo dough are permeable, allowing the honey to soak through. But software abstractions are best when they don’t leak. When you pile layer on top of layer in software, the layers are bound to leak.

15. Hindenbug

Oh-the-huge-manatee

A catastrophic data destroying bug. “Oh the humanity!”

Also related to Counterbug (a bug you present when presented with a bug caused by the person presenting the bug) and Bloombug (a bug that accidentally generates money).

16. Fear Driven Development

Youre-fired

When project management adds more pressure (fires someone, moves deadlines forward, subtracts resources from the project, etc).

17. Hydra Code

800px-Hercules_slaying_the_Hydra

Code that cannot be fixed. Like the Hydra of legend, every new fix introduces two new bugs. It should be rewritten.

18. Common Law Feature

anonymous

Common-law-marriage

A bug in the application that has existed so long that it is now part of the expected functionality, and user support is required to actually fix it.

19. Loch Ness Monster Bug

Loch-ness-monster

I’ve started Loch Ness Monster bug for anything not reproducible / only sighted by one person. I’m hearing a lot of people in the office say it now. (Possible alternates: Bugfoot, Nessiebug.)

20. Ninja Comments

Ninja-comments

Also known as invisible commentssecret comments, or no comments.

21. Smurf Naming Convention

sal

When almost every class has the same prefix. IE, when a user clicks on the button, a SmurfAccountView passes a SmurfAccountDTO to the SmurfAccountController. The SmurfIDis used to fetch a SmurfOrderHistory which is passed to the SmurfHistoryMatch before forwarding to either SmurfHistoryReviewView or SmurfHistoryReportingView. If a SmurfErrorEvent occurs it is logged by SmurfErrorLogger to ${app}/smurf/log/smurf/smurflog.log

22. Protoduction

A prototype that ends up in production. Heard this from a tech at the Fermi lab. He said he didn’t coin the term but had heard it used a number of times at Fermi.

23. Rubber Ducking

Sometimes, you just have to talk a problem out. I used to go to my boss and talk about something and he’d listen and then I’d just answer my own question and walk out without him saying a thing. I read about someone that put a rubber duck on their monitor so they could talk to it, so rubberducking is talking your way through a problem.

24. Banana Banana Banana

Placeholder text indicating that documentation is in progress or yet to be completed. Mostly used because FxCop complains when a public function lacks documentation.

/// 
/// banana banana banana
/// 
public CustomerValidationResponse Validate()

Other food-related jargon: Programmer Fuel (Mountain Dew, coffee, Mate, anything which gets you well-caffeinated), Hot Potato (Http and Https respectively. Same number of syllables, but more fun to say), Cake (Marty’s noob cake broke the build), Chunky Salsa (based on the chunky salsa rule, a single critical error or bug that renders an entire system unusable, especially in a production environment).

25. Bicrement

Adding 2 to a variable.

26. Reality 101 Failure

The program (or more likely feature of a program) does exactly what was asked for but when it’s deployed it turns out that the problem was misunderstood and it’s basically useless.

27. Mad Girlfriend Bug

When you see something strange happening, but the software is telling you everything is fine.

28. Megamoth

Stands for MEGA MOnolithic meTHod. Often contained inside a God Object, and usually stretches over two screens in height. Megamoths of greater size than 2k LOC have been sighted. Beware of the MEGAMOTH!

29. Hooker Code

Code that is problematic and causes application instability (application “goes down” often). “Did the site go down again? Yeah, Jim must still have some hooker code in there.”

30. Jenga Code

When the whole thing collapses after you alter a block of code.

This is just the top 30, what I consider to be the most likely candidates for actual new programming jargon based on community upvotes, not just “funny thing that another programmer typed on a webpage and I felt compelled to upvote for hilarity”. Because that would be Reddit. If you’re itching to see even more, there are plenty more answers to read – three hundred and fifty six more to be precise. Longtime Stack Overflow user Greg Hewgill maintains , but this one hasn’t quite made it in there yet. In the meantime, try Stack Printer, or if you have the requisite 10k rep on Stack Overflow, you can view the full soft-deleted question on the site.

HTTP Strict Transport Security

Here’s another gotchas (and novel feature) of the internet world: HSTS (Http Strict Transport Security).

Basically a website can provide a Strict-Transport-Security response header to force the browser to use HTTPS automatically for all subsequent request for a duration of time.

hsts

The response header above says for the next 31536000 seconds (1 year), the browser has to use HTTPS to access this domain, and all its subdomains.

This becomes a gotcha if you’re testing a new subdomain over HTTP by updating your local host file, you might be wondering why your browser wouldn’t let you to connect using HTTP immediately — without consulting with the web server first.

Fortunately it can be overcame by simply clearing your browser cache.

Using Boost On Visual Studio Project

To use Boost libraries, set following configurations on Visual Studio project properties:

  1. Check if boost is already installed (eg: C:\Program Files (x86)\boost\boost_1_51_0) if not, go through the installation process on http://www.boost.org/doc/libs/1_52_0/more/getting_started/windows.html
  2. Ensure BOOST_HOME environment variable exist and points to the installation path above
  3. On project properties, under C/C++ -> General, add $(BOOST_HOME) to Additional Include Directories
  4. Under Linker -> General, add $(BOOST_HOME)\lib to Additional Library Directories
  5. Ensure C/C++ -> Code Generations -> Runtime Library is set to /MD or /MDd so linker can find boost lib files

Some boost component such as boost log need to be built first before it can be linked:

  1. Unarchive the downloaded compressed file
  2. Open command prompt in administrator mode and cd into the unarchived directory. Run bootstrap.bat to build b2
  3. Run b2 install --prefix=PREFIX --toolset=msvc-10.0 --build-type=complete stage. This will take about 30 minutes, be patient. Note: “PREFIX” is the directory you want to install boost (eg: lib). “toolset=msvc-10.0″ means compile boost by using visual studio 2010.

Showing Geographical Location On Google Map (Geocoding)

Translating a geographical location such as “London, UK” into a lat/long coordinate (lat: 51.5085150, long: -0.1254870) is called geocoding. This coordinate can then be used to display the location on google map.

Try putting a location in the box below and hit go:

Register for Google Map API Key

In order to implement the above widget first obtain an API key from Google:

  1. Go to
  2. Select Services on the left menu, ensure Geocoding API, Google Maps Embed API and Google Maps JavaScript API v3 are turned on

    geocoding1

    geocoding2
  3. Go to API Access, select Create new Browser key

    geocoding3
  4. The list of accepted HTTP referers will be asked, if you’re testing on local machine this would probably be localhost/*, otherwise you need to put your website domain name here. Hit Create once you’re done

    geocoding4
  5. Take a note of your API key, this will be used in the later part of this tutorial

    geocoding5

The HTML Code

This widget only contains 3 elements:

  • A text input box to provide the geographical location
  • A button to submit the address and show it on the map
  • A div container for the map
Enter location (eg: London, UK): 


Javascript

2 javascript libraries are used: jQuery and Google Map JS. The key parameter on the Google Map JS URL should be the key created above.


Firstly let’s initialize the div container so it doesn’t come up with blank map, here I set it into coordinate of San Francisco, CA:

$(document).ready(function() {
        var map = new google.maps.Map($('#map')[0], {
                center: new google.maps.LatLng(37.7749295, -122.4194155),
                zoom: 8
        });
        ...
}

And create a click handler for the ‘Go’ button which sends ajax post into Google Map JS API. The API will return a JSON response with the location if successful.

$(document).ready(function() {
        ...
        $('#go').click(function(e) {
                e.preventDefault();
                var loc = $('#loc').val();
                $.ajax({
                        url: '//maps.googleapis.com/maps/api/geocode/json?sensor=false&address='+loc
                }).done(function(data) {
                        if(data.status != "OK") {
                                alert("Unable to find location");
                                return;
                        }
                        var loc_result = data.results[0].geometry.location;
                        map.setCenter(new google.maps.LatLng(loc_result.lat, loc_result.lng));
                });
        });
});

See the widget in action in full screen.

What’s The Deal With Half Up and Half Even Rounding?

java.math package came with several rounding mode but there are 2 quite interesting ones: HALF_UP and HALF_EVEN rounding.

HALF_UP

This is basically your elementary school rounding. If the fractions to be rounded are equidistant from its neighbor, then round them into the upper neighbour. In other words, if we’re rounding 1 digit after decimal, then if it ends with .5 just add .5. For example:

Fractional Number Rounded
0.1 0
0.5 1
1.3 1
1.5 2

HALF_EVEN

Similar like HALF_UP, except if the fraction is equidistant, round them into nearest even neighbor. For example:

Fractional Number Rounded
0.1 0
0.5 0
1.3 1
1.5 2

Why Bother With HALF_EVEN?

Why don’t we just stick with what’s learned in elementary school? Well here’s one good reason: accumulative error. Error here means “How much did we lose/gain by rounding the number?”. Let’s take a look again to both table with its rounding error displayed

Fractional Number HALF_UP rounding HALF_UP rounding error HALF_EVEN rounding HALF_EVEN rounding error
0.0 0 0.0 0 0.0
0.1 0 -0.1 0 -0.1
0.2 0 -0.2 0 -0.2
0.3 0 -0.3 0 -0.3
0.4 0 -0.4 0 -0.4
0.5 1 0.5 0 -0.5
0.6 1 0.4 1 0.4
0.7 1 0.3 1 0.3
0.8 1 0.2 1 0.2
0.9 1 0.1 1 0.1
1.0 1 0.0 1 0.0
1.1 1 -0.1 1 -0.1
1.2 1 -0.2 1 -0.2
1.3 1 -0.3 1 -0.3
1.4 1 -0.4 1 -0.4
1.5 2 0.5 2 0.5
1.6 2 0.4 2 0.4
1.7 2 0.3 2 0.3
1.8 2 0.2 2 0.2
1.9 2 0.1 2 0.1
2.0 2 0.0 2 0.0
Total 1 0 0

As you can see the accumulative errors for HALF_UP is incrementally higher whereas HALF_EVEN averages out. This is why HALF_EVEN is often called “Banker’s rounding” because given a large amount of data the bank should not gain/loss money because of rounding.

More Surprises With printf

Don’t yet assume all programming language defaults into HALF_EVEN, try below examples of printf in your shell:

$ printf "%.5f" 1.000015
1.00002
$ printf "%.5f" 1.000025
1.00002
$ printf "%.5f" 1.000035
1.00004
$ printf "%.5f" 1.000045
1.00005

Wait.. what? Isn’t 1.000045 supposed to be rounded to 1.00004? Well in floating point realm the reality is more complicated than that, taking into account floating point is often never accurate in the first place.

Try printing 1.000045 with long enough digits after decimal:

$ printf "%.30f" 1.000045
1.000045000000000072759576141834

Now you can see computers can’t always store accurate value of real numbers in floating point types. (And you should now see why it’s rounded into 1.00005)

Here’s some reading if you’re interested in this problem.