Your favorite left sidebar content goes here




Making the Simple Complicated

A new favorite site of mine is The Daily WTF. It’s chock full of hilarious stories: some almost anyone can understand, and others only experienced IT professionals can. This gem is particularly amusing:

It never ceases to amaze me the lengths that certain programmers will go to solve the simplest of problems. Like, say, negation.

When “n * (-1)” Won’t do …

Originally published on August 12, 2004.

… just come up with an overly complicated function that achieves the same thing, like this one discovered by “mightydog”:

If you can understand pseudo-code you should be fine, VB.NET is decently readable: this is a really complicated way of changing a number’s sign.

I was wondering, how many ways could I come up with to do this? What is the most complicated way I could think of? I decided that by complicated, I didn’t mean how many unnecessary lines of code I could throw in (like arbitrary IF statements), just how complicated could I make the algorithm.

I came up with 4 ways. Two are identically simple, one isn’t that bad (it still is only 1 line of code) but the final is just silly.

        public double ChangeSign1(double iDouble)

        {

            return (-1) * iDouble;

        }

 

        public double ChangeSign2(double iDouble)

        {

            return 0 - iDouble;

        }

 

        public double ChangeSign3(double iDouble)

        {

            return iDouble - 2 * iDouble;

        }

 

        public double ChangeSign4(double iDouble)

        {

            double tempDouble = 0;

            if (iDouble > 0)

            {

                for (int i = 1; i <= iDouble; i++)

                {

                    tempDouble–;

                }

            }

            else if (iDouble < 0)

            {

                for (int i = -1; i >= iDouble; i–)

                {

                    tempDouble++;

                }

            }

            tempDouble -= iDouble - Math.Truncate(iDouble);

            return tempDouble;

 

        }

So #4 is the most complicated way I could think of to change the sign of a number. More lines of code could be written, making it seem more complicated, but I can’t think any way that’s more complicated in the actual calculation that is more complicated.

[12/30/2008 sorry about the formatting, I’ll fix it later]

[12/31/2008 somewhat updated formatting, but this version of wordpress keeps removing things I attempt to do]

[12/31/2008 Silly math error in #4, when rounding up it doesn’t work out right…DOH — Fixed, changed Round to Truncate]


1 Response to “Making the Simple Complicated”

  1. 1 Frankie

3K2 theme by Hakan Aydin