Skip to content
News: Sensation!!! Calculator consolidation loan student Corporate credit rating Credit online report Consolidate graduate loan student Online credit card processing services Bad auto loan credit lead Home loan sacramento How to lower credit card interest rate Business to business credit union Card company complaint credit Best card credit low rate 0 finance credit card Card credit increase minimum payment Credit free free online report No credit card car rental Bad credit mortgage lender Poor credit home loan Canadian secured credit card Consumer credit counseling debt consolidation Sterling bank secured credit card Home improvement loan lender Connecticut bad credit mortgage Pennsylvania debt consolidation loan Hypercom credit card machine Payday advance loan illinois Accepting business card credit small Build business credit National consumer credit Online credit card casino Consumer credit law Instant decision credit card Credit card debt calculator Loan rate home equity loan Military bad credit personal loan California home loan veteran Refinancing and home improvement loan Monogram credit card bank Low interest rate credit card Georgia home loan Com credit report Travel reward credit card Consolidation loan debt reduction Calculate credit score Consumer credit info Jacksonville home equity loan Loan online personal unsecured Consumer credit online report Home loan manufactured va Unsecured business loan bad credit Card consolidate credit payment Credit card transaction processing California equity home loan online Airline miles credit card Bad credit home loan mortgage quote Fast private student loan Excessive credit card debt Free porn movie no credit card Merchant account credit card processing Online credit counseling Eliminate credit card debt Manufactured home loan Cash back business credit card 3 credit report How to get a credit card with no credit history Payday loan application Card counseling credit debt services Federal direct student loan program Federal student loan forgiveness Credit card depot and debt consolidation Business debt consolidation loan Card consolidation credit Atlanta debt consolidation loan Citibank credit card customer service High risk credit card processing Christian debt consolidation Bad credit down home loan money no Credit free massachusetts report Apply for a visa credit card online Card company credit minimum payment raising Credit free line report Fix bad credit Secured credit card fast Beat credit card debt Consolidation defaulted loan student Free credit card report Card card com credit hsbc Online va home loan Whats a good credit score Card credit credit free report Providian credit card services Bad credit mortgage quote Federal consumer credit protection act No faxing instant payday loan California home loan manufactured 1st financial bank credit card Federal home loan bank rate Ditech from home loan mortgage second Credit card merchant account Prepaid travel credit card Card credit credit score Visa credit card machine Credit report credit score Bad card credit gas Payday loan utah Bad capital card credit credit one First horizon home loan corp Consolidation counseling credit debt Lexington credit repair Master card credit application Major credit card company Personal loan unsecured no credit check Credit card debt consolidation loan Home loan cleveland ohio Capitol one secured credit card Free prepaid credit card Lipman credit card machine Acs consolidation loan student Personal car loan Partially secured credit card Student loan consolidation center Eliminating credit card debt Self credit repair Student credit card uk Us bank credit card Cash advance payday loan Airline card credit mile offer Online credit card processor Chase credit card bill pay Payday loan No credit card required credit report Uk personal loan online Instant approval payday loan Mobile home refinance loan Credit debt management Free credit rating check Erase bad credit Debt consolidation for people with bad credit Bad credit help Cash back credit card application Payday loan personal Bad business card credit credit Consolidation loan services student Home equity loan comparison One time free credit report Indiana bad credit auto loan Credit report score Credit repair report Card credit customer discover service Mobile home loan Card consolidation credit debt help Credit score rating scale 0 apr credit card Miami home equity loan Accept credit card transactions Washington home equity loan 3 in 1 credit report Alliance credit counseling Calculator consolidation debt loan student Calculator card consolidation debt credit California credit repair Oklahoma department of consumer credit Secured credit card instant approval Consolidation federal loan program student 0 credit card offer Calculator card consolidation credit debt Texas home loan Arizona credit free report Credit free repair report Sunoco gas credit card Wal mart credit card services Equity home interest loan only Online debt consolidation program Card consolidation credit debt services Card consolidation credit debt oregon Jc penney credit card application Reduce credit card debt Banks who offer secured credit card Canadian credit free online report Credit free government report us Good credit score number Bad consolidation credit loan people Chase credit card online payment Instant credit approval credit card Card credit low rate San diego home equity loan Card consolidation credit debt service Low apr visa credit card Secured corporate credit card Card credit instant virtual Government grants on student loan 1000 advance loan payday Annual credit report trans union Providian credit card payment Credit card visa master card First national merchant credit card Perfect credit score Wal mart credit card application Home loan low mortgage rate Absolutely credit free online report Credit repair help Direct merchant credit card bank na Cheap credit card deal Compare credit card Chicago counseling credit Countrywide home inc loan Secured credit card offer Credit free michigan report Apply online kohls credit card 3 bureau credit report with score 125 home equity loan Mobile home refinancing loan Home interest loan mortgage only Student loan for student with bad credit Capital one student credit card Free annual credit report with experian Cheap credit card company Low rate home equity loan Bad credit student personal loan Best secured credit card deal Bad card credit credit people unsecured Loan online personal uk Application bad card credit credit Apply bad canada card credit credit in Advice blog consolidation debt Bad credit need a personal loan Approval card credit credit instant Bad credit loan mortgage uk No fee secured credit card uk Cheap credit card rate Online credit report canada Best business credit card Free sex video no credit card Credit card company rating Credit score Louisiana home equity loan Business credit report repair Card chase credit service Low interest credit card Lending loan online personal Balance card credit deal transfer Free consumer credit report Credit card reward program Bad credit mortgage Credit card for student with bad credit Debt consolidation services Find out my credit score for free Low apr credit card uk Discover credit card phone number Loan student Christian credit counseling Credit history report online Cambridge credit counseling Consolidate credit card debt Debt consolidation home equity loan Bureau credit score No credit check payday loan California home loan mortgage rate 3 bureau credit free report Best airline reward credit card Credit report score understanding Business line of credit Debt consolidation home mortgage loan Providian visa credit card Interest loan low student Best credit card reward program Credit card debt consolidation company Loan mae sallie signature student Christy canyon on video no credit card New jersey home equity loan Debt consolidation mortgage California home mortgage loan rate Credit card business opportunity Understanding credit score Apply for student credit card Delta airline credit card Bad credit home loan mortgage Consolidation debt loan student Approval card credit instant Quickly improve my credit score Bad card credit credit loan Pay capital one credit card bill Instant approval credit card Bad credit personal signature loan Bad credit re mortgage uk California home loan rate refinance Online business credit card deal Cheap unsecured personal loan Low credit score Best buy card credit services Household bank credit card services Consumer credit council Citibank secured credit card Bad card credit credit unsecured Legal credit repair Auto bad credit florida loan Bank of america credit card online Amex apply card credit Can credit card company garnish your wages Apply credit card on line Consolidation federal loan non student 0 transfer credit card Used credit card machine Home improvement loan Arizona home loan online Compare credit card offer Capital one credit card canada Bankruptcy card credit unsecured Visa reward credit card Citibank credit card login Visa credit card numbers Consolidation debt information Business credit rating Free sex web cam with no credit card 0 percent credit card offer Chase manhattan credit card Consumer credit counseling of atlanta 1 3 credit free in report Alternative consolidation loan student Student credit card apply online Instant approve credit card Visa credit card for bad credit Free credit card processing Online home loan Credit card machine retail Bad credit florida loan mortgage Debt consolidation loan without owning a home Unsecured credit card application Car loan bad credit history Credit free report yearly Short term payday loan Building business credit Apply best buy card credit Citibank student loan corporation Best card credit rate secured Credit free one report time Business credit score Alternative student loan for bad credit Federal student loan program New home buyer loan florida Apply business card credit small Private student loan consolidation Texas va home loan Accept credit card on your web site New york mortgage home loan Payday loan no faxing cheap Free debt consolidation help Student loan for people with bad credit Card credit search uk Online credit card payment Best home loan mortgage rate Business credit card with reward Completely credit free report Qualify fha home loan Commercial credit counseling Credit card debt advice Apply card credit online secured Card consolidation credit help Capital one credit card uk Instant bad credit loan Fast bad credit personal loan Card credit fraud history Purchase prepaid credit card Unsecured credit card debt consolidation Card credit pal pay prepaid Credit card processing information Secured uk home loan Article credit card debt Credit free nc report Business card credit start up Best credit card benefit Bad credit mortgage uk Free phone no credit card required Minnesota home improvement loan Poor credit rating loan Credit repair book En language loan personal Card credit payment sears Card credit credit free report without Merrick bank credit card Card credit payment service Student loan consolidation Debt consolidation firm Payday loan in canada Free online credit report canada Copy credit free instant report Credit card application on line Approval bad card credit credit instant online Bad credit credit card no deposit Bad credit refinance Credit card processing software Compare credit card rate Credit repair law firm Self help credit repair 0 apr intro credit card Consolidation debt graduate loan student Bad credit home mortgage loan Free online credit report without credit card Credit equifax number phone report Card compare credit offer online Prepaid credit card deal Auto loan bad credit car loan Credit free no obligation report Credit free ftc report Pennsylvania bad credit mortgage American express business credit card Florida mortgage home loan Trafalgar home loan Second mortgage versus home equity loan Bad credit debt consolidation Guaranteed loan student texas Household credit card services New millennium bank credit card How to read an experian credit report Business card credit gm Amazon card chase credit Comsumer credit counseling Consolidation credit debt Reward 660 credit card Credit card reward Home loan Home equity loan kentucky Chase reward credit card Card credit fixed low rate Consolidation debt free non profit Payday loan store Consolidating loan student Consumer report best credit card High credit score Apply online credit card application New mexico home equity loan Card credit name number South carolina student loan corporation Default student loan consolidation Bureau credit report Free trans union annual credit report First time mortgage bad credit Loan and debt consolidation finance Annual credit equifax free report Debt consolidation loan for people with bad credit Home equity loan uk Bad credit special finance car loan Credit instant online report Bad credit business credit card No credit needed credit card Bad credit mortgage refinancing .com credit report Day loan payday quick same Apply bad card credit credit Eon bank credit card Manual credit card machine Application card college credit student Bad car credit financing loan Federal student loan payment Consolidation consumer counseling credit debt Credit repair lawyer New home construction loan rate Credit equifax online report Colorado credit free report Credit score range First time home loan Home equity loan tax deduction 0 interest rate credit card Debt consolidation program Centered christian consolidation debt Accept credit card without merchant account Bad credit home loan mortgage services Card consolidation credit debt free 0 interest credit card transfer balance Secured personal loan bad credit Bad credit fair loan mortgage Experian credit report dispute Best consolidation loan student United airline credit card Loan services student Ameriquest card card credit master platinum Best card credit interest low Minnesota home loan Chase.com credit card Credit report tenant Credit score and mortgage rate First premier credit card login Bankruptcy personal loan Credit repair software Home improvement interest loan rate Bad credit 2nd mortgage Improve credit score fast Credit card debt consolidation Mortgage with bad credit chicago 3 credit free report Credit help poor Card credit number online Account loan payday savings Credit card debt bankruptcy Bad credit home loan mobil Credit card and student loan consolidation Michigan debt consolidation Bad credit home loan missouri Countrywide home loan servicing Providian secured credit card Bad credit unsecured personal loan Card credit first premier secured Home loan loan mortgage refinance Credit card reader Best credit card for bad credit Free credit counseling Apply card credit virgin Card consolidation credit debt management Approval card credit instant offer Cash fast loan online payday Credit repair after bankruptcy Gm master card credit card Free uk online credit report Lowest home equity loan Instant approval credit card canada California equity home loan mortgage Card credit credit poor unsecured No equity debt consolidation loan Online debt consolidation Bankruptcy equity home loan Live debt consolidation lead Small personal loan bad credit Personal credit rating Balance card credit interest low transfer Fraud credit card company Debt consolidation loan online uk Card company counseling credit Bad credit mortgage rating Bad credit checking account Royal bank of scotland credit card Bad credit home improvement loan Home loan rate Accept credit card hardware Free credit report without a credit card Student credit card instant approval Bad card credit credit no Fleet credit card online Credit card processing system Personal loan for very bad credit Credit card debt loan Card credit processing service Cash fash loan payday Debt consolidation home mortgage loan Card compare credit different from offer Credit repair counseling Credit score calculator Bad card credit credit uk Equity florida home in loan Low fixed apr credit card Alternative loan student Home interest loan mortgage rate Consumer credit repair Bad credit loan Business credit express Consolidation credit debt repair Uk no credit check credit card Canadian international loan program student Apply for credit card instant approval Fast cash advance payday loan Consumer credit debt consolidation Instant credit card number Card credit uk unsecured Consolidation loan personal student Corporate credit card uk Personal secured consolidation loan uk Home equity loan No balance transfer fee credit card Bad credit high limit credit card Card credit depot home payment Accelerated debt consolidation Small business loan bad credit Letter to credit card company Florida debt consolidation loan Bad bankruptcy credit home loan Bad credit loan mortgage people Bank federal francisco home loan san Cheap payday loan online Omni 3200 credit card machine Credit card for online shop Free consumer credit counseling How to get a home loan with bad credit Credit card reward point Consolidate credit card Instant approval bad credit credit card First time home buyer loan Debt loan negotiation student Free porn no credit card required Loan people student Credit score 650 Business card credit interest low 100 bad credit financing mortgage Premier credit card Federal student loan information Nova credit card processing Loan student subsidized Apply card credit macys Credit card for people with no credit history Trans union credit report bureau Faxless loan payday quick Consolidation credit debt help Credit card and student loan consolidation Whats my credit score Credit card debt consolidation service Va home mortgage loan rate Credit card repair Free sex movie no credit card Consolidation federal loan student Best credit card deal uk Free trans union credit report Online student loan consolidation Business credit en language report Personal student loan Consumer credit free report Repair credit repair credit Card card continental credit finance master Free credit report com American express secured credit card Bad credit florida in loan mortgage Credit card processing account Low cost payday loan Shell credit card account Credit card debt consolidation oregon First premier credit card Equity florida home loan refinancing Balance card credit low transfer Credit card application for bad credit Apply canada card credit new york Debt consolidation defaulted student loan Lexington law credit repair Credit card processing canada Free credit check no credit card needed Bank of america credit card account 0 business card credit Government home improvement grants loan Ohio home equity loan rate College debt consolidation Card credit service Credit equifax from report Atlanta home loan Approval card credit guaranteed instant Home equity loan in california Home equity loan pro and cons Business credit free report Student loan debt consolidation Debt consolidation counseling services Bad credit repair report Quick cash payday loan Bad credit mortgage wisconsin Personal debt consolidation Student loan people Bad card company credit debt Bad credit personal loan lender 0 apr business card credit Credit card with a bad credit rating Bad credit home loan texas Debt management credit counseling Visa credit card offer Business debt consolidation On line credit card processing Credit card machine Bad credit rv loan Guaranteed loan personal unsecured Discount credit card processing Credit card processing machine 678 average credit score us Hsbc credit card india Home loan mortgage rate Bad consolidation credit debt loan Card consolidation credit uk Low fee payday loan California home loan purchase Consumer credit counselor Va home loan lender Trans union personal credit report Card com credit mbna Credit card processing low rate No transfer fee credit card Sears credit card Colorado debt consolidation loan Baby phat prepaid credit card Bank card credit first payment premier Uk credit card apply Wholesale manufactured home loan Card credit debt help judgment Bad credit rating Bad credit car finance Fha government home loan Credit rating fix National student loan canada Unsecured personal loan australia Capital one bank credit card 0 credit card application California home in loan Mortgage credit rating Annual credit free law report Debt consolidation credit counseling Center consolidation loan student Bad credit fast cash loan Card credit emerge payment Consolidate consolidation credit debt Home equity loan vs home equity line of credit How to read a trans union credit report Medical student loan consolidation Printable credit card application Home loan for home improvement Low rate credit card offer Free credit rating Applicant bad credit loan mortgage Trans union credit report dispute Balance card credit offer transfer Credit repair secret Credit score meaning Credit instantly online report Instant faxless payday loan Approval bad card credit credit instant people Countrywide home loan Texaco shell credit card Free music download no credit card Florida home improvement loan Bad credit repair service International prepaid credit card Fixed home equity loan Student loan consolidation loan California bad credit mortgage Citi credit card online Credit card for those with bad credit 1000 loan no payday telecheck Home loan for people with bad credit Student loan consolidation incentive Credit counseling service Instant online approval credit card Bad credit Credit free online report totally No fax payday advance loan Card consolidation credit debt online Fast cash personal loan Christian counseling credit houston South carolina bad credit mortgage Loan home mortgage rate in california Banks that offer secured credit card College student loan consolidation Refinance mortgage loan home rate Clean credit report

When Ants Come to Your Picnic

Since I posted my "Sling Blade Runner" answer, I've been in discussion with Benjamin Meyer about the puzzle, my solution, and other general topics. During this discussion, he shared his solution with me, and as a collaboration, we found a set of movie titles that is 326 movies long. The original list of 318 movies was generated by my program, but was expanded to 326 by his. (My algorithm is good at finding long lists, his algorithm is good at optimizing long lists.)

I've decided that since I've shared much of the algorithm with him (not my code), that I would publish my answer here as well.

The algorithm I used is called Ant Colony Optimization (ACO). ACO is a randomized algorithm where virtual ants walk a graph of the problem space developing answers. Once a number of ants have walked the problem, they lay a "pheromone" on the "paths" that were particularly good. The algorithm then has more virtual ants walk the problem space, but this time they "slightly favor" paths that have pheromone on them. Once the second round of ants finishes, all pheromones on the problem are faded, and the best ants from the second run lay their pheromone. A simple state machine describes ACO's operation:

  1. Allow N ants to randomly walk your problem. The probability that an ant will take a certain turn in the path is a combination of an apriori probability and a weighting probability from the pheromones laid on the particular edge.
  2. Fade all pheromones on the edges.
  3. For the M best ants, allow them to lay the pheromones.
  4. Goto (1) until you think you've got a good path.

ACO is devilishly simple in its implementation, develops surprisingly good answers to this problem, and is highly threadable. But, ACO does come with its own set of drawbacks -- in particular there are a number of "magically tuned" parameters that affect its operation:

  1. What is a good number of M and N?
  2. What is appropriate amount of pheromone for "good" ants to lay?
  3. What is a good way to combine the apriori and pheromone probabilities?
  4. What is a good apriori probability?
  5. And finally, How much do you fade all the different pheromones between steps?

Unfortunately, ACO doesn't give us much help with many of the above problems. That didn't phase me, I just charged ahead and threw some ants at my problem. :)

In my source directory, you will find a copy of my source code that implements Ant Colony Optimization of Sling Blade Runner. There are a number of different comments I'd like to make:

  1. Unlike Ben's clever solution, I didn't bother to thread it. It would be easy enough to do, I didn't bother.
  2. There are a number of optimizations in this code. Namely, I stripped out ACO's call to the pow function, and made them lookup tables, and rejiggered things to minimize copying things to and from the stack.
  3. There are a number of optimizations I didn't make. Namely, I call new (through push_back/push_front) in my main loop. That's just plain silly, but I didn't bother to strip it out.
  4. My magical parameters were tuned by trial and error. Most of them are #defines, and if you read the ACO literature, you can understand my nomenclature.
  5. The code isn't the most readable. I coded it quickly, and have tweaked it. It's only a personal project, so don't hate me because it ain't beautiful. :)

Having implemented ACO, I can say that it's an interesting idea, and one I'm happy to have in my arsenal. It codes up quickly, and I have already used it to solve a couple of other problems of varying complexity.

Edited to add:
You'll need the movies data to run my program.

Sling Blade Runner

Lately, I've been without a project to keep me busy at nights (hence all my blog posts). I'm learning python, but since my main gig is C/C++, I like to keep those skills sharp with little puzzles. While looking for interesting coding puzzles, I stumbled across a page at ITA Software that asks you to find the longest chain of movies you can. For example, "Sling Blade Runner" are two titles strung together. Seemed simple enough at first blush, but once you study the problem some, you realize it's much harder than originally thought.

So, I sat down and started hacking. Since the puzzle is a recruiting tool, I won't spoil it by giving my code, but I came up with a solution that seems to be the best one published on the web at this time.

My code averages around 270 per run, and runs take about 5 minutes. My solution is heuristic, and is guaranteed to find the longest answer, but you might have to wait till the sun swallows your computer before it finds it.

Just to throw down the gauntlet, I submit my longest movie string found (during a standard 5 minute run) -- 304 movies.

Editted to add:
It's surprising how often this movie ends up in a list. (Props to Kevin James Barker!)

Re-editted to add:
Well, It looks like I'm not King of the Hill any longer (see the comments). I guess I should get back to work on this puzzle.

Beautiful Code

Recently, my wife and I went to the local Borders, and I saw O'Reilly's Beautiful Code. Since the book has sat in my Amazon queue for months, I was excited to get a chance to peruse it. So, I gleefully sat down, cracked the cover, and proceeded to read a number of chapters.

I'll save you some time and just tell you that the book was supremely disappointing. With the exception of the first chapter, I felt the book was entirely "missable". In fact, I would venture to say that the only piece of truly "Beautiful Code" I found in the whole book would be Brian Kernighan's (with help from Rob Pike) regular expression engine. To me, it is an inspired piece of code. It shows a simple regular expression engine in 30 lines of C code. It shows the beauty and power of C with a practical and elegant solution to a real world problem. Wow.

Now, I admit, not everyone is Brian Kernighan or Rob Pike, but I felt let down by Beautiful Code. I felt most of the submissions were just pieces of code that the authors yanked from their projects and decided to talk about. None of them were as generic, widely applicable, or beautiful as that by Kernighan.

I might end up buying Beautiful Code anyway since it's for a good cause. I doubt I'd ever re-read it though.

Safe Mutex Management

Recently, I've been writing a fair amount of threaded C++ POSIX code, and (as I often do), I decided to wrap the POSIX mutexes in a convenient little wrapper class:

 
class Mutex
{
    pthread_mutex_t mMutex;
public:
    Mutex() { pthread_mutex_init(&mMutex, NULL); }
    ~Mutex() { pthread_mutex_destroy(&mMutex); }
 
    void Lock() { pthread_mutex_lock(&mMutex); }
    void Unlock() { pthread_mutex_unlock(&mMutex); }
    bool TryLock() { return (pthread_mutex_trylock(&mMutex) == 0)?(true):(false); }
};
 

I know others' opinions differ, but I personally like wrappers like this. They allow me a nice way to make sure that all my Mutexes are friendly C++ objects, play well as member variables, etc.

While writing some code, I caught myself writing a number of functions like the following:

 
void MyClass::MyFunc()
{
    mMutex.Lock();
    if (SomeCondition())
    {
        if(SomeOtherCondition())
        {
            // etc...
        }
    }
    mMutex.Unlock();
}
 

Now, whenever I write code like the above function, it makes my skin crawl. First of all, I hate writing nested if statements. Secondly, and more importantly, the above code is exception unsafe in that if any of the code before the mMutex.Unlock() throws an exception, the mutex won't be unlocked correctly.

First I thought that since I don't care about the exception in MyFunc(), I could get away with:

 
void MyClass::MyFunc()
{
    mMutex.Lock();
    try
    {
        // etc...
        mMutex.Unlock();
    }
    catch(...)
    {
        mMutex.Unlock();
        throw;
    }
}
 

But, I hate the multiple calls to unlock the mutex, the unneeded try/catch block, and just everything about this code.

After some thinking, I came to a conclusion, that in hindsight must be obvious to most C++ programmers out there:

 
class SafeLock
{
    Mutex &mMutex;
public:
    SafeLock(Mutex &inMutex) : mMutex(inMutex) { mMutex.Lock(); }
    ~SafeLock() { mMutex.Unlock(); }
};
 

Now all I need to do is the following:

 
void MyClass::MyFunc()
{
    SafeLock lock(mMutex);
    if(!SomeCondition()) return;
    if(!SomeOtherCondition()) return;
    // etc...
}
 

Additionally, I have found that SafeLock makes it easier on me to call functions that require a mutex to be held before calling it. I just pass references to the SafeLock to all functions that require the mutex held:

 
void MyFuncThatRequiresMutex(const SafeLock &lock)
{
    (void)lock;
    // etc...
}
 

Torch Singer

These things crawl across my floor, I can't use them anymore.
There's a heaven in her band, Hallelujahs in my hand.
All my patience, love's inside -- she just climbed the stairs and died.
Lights that rose, and fell again, songs that thinned out near the end.

Her voice trailed off in the end.

Though your miles are more than mine -- the things I've taken in a bind.
It's for certain, it's for sure... I've no use for them no more.
Making room within one's self, for another's song to help
And it all comes back to me, as I walk hungover down the street.

And it all comes back to me.

And it all comes back to me, as I walk hungover down the street.
She's a mother in disguise, I look different in her skies.
But, it's morning, so I say, "It's a big red letter day."
Her skin's whitewash like skim milk, her words sing softly just like silk.

There's some things I've got to say, she won't understand anyway.
There are miles between our hearts, there's salvation in false starts.

I'm forsaken, in the end.


I'm sorry I missed them.

Escaping the MTRX

Embedded developers have it harder than most. Often we don't have library options most other developers do. For example, the library might depend on file I/O, or it might require easy access to a large heap, or it even might require floating point arithmetic that our part is no good at implementing in software.

Overtime we learn to adapt and overcome. We develop a set of libraries which performs most of the functionality we need. We find good articles in different embedded magazines that have code we can rip off. And we even sometimes suck it up, and buy better parts or operating systems to make development easier.

Over the recent months, I've been re-tweaking a simple set of C matrix functions I've used before. The library is specifically designed for embedded developers. What I mean by that is I tried to follow a number of goals:

  • The library should be optimized for readability/portability.
  • Don't try to be all things to all people, provide the basic functionality people will require for one and two dimensional matrices.
  • Don't require a heap.

The following is my MTRX library:
mtrx.h
mtrx.c

The library provides the basic matrix functionality like:

  • Scalar addition, subtraction, and multiplication
  • Multiplication
  • Inversion
  • In-place and out of place transposition

I haven't extended it to include eigenvalues and vectors. Additionally, I haven't added different matrix decompositions that others might need. Again, the library is a barebones matrix implementation that most embedded developers can use with a little tweaking.

Here's an example of using the library:

 
#include "mtrx.h"
#include <stdlib.h>
#include <time.h>
 
#define N (100)
 
int main()
{
	unsigned i,j;
	srand(time(0));
	for(i = 0; i < 1000; ++i)
	{
		MTRX_t			m1, m2, m3;
		MTRX_Element_t	f[N * N];
		for(j = 0; j < N * N; ++j)
			f[j] = ((float)(rand())) / ((float)RAND_MAX);
		MTRX_Create(&m1, N, N, f); // will use the stack's f[] for storage
		MTRX_Create(&m2, N, N, 0); // uses the heap
		MTRX_Create(&m3, N, N, 0); // uses the heap
		MTRX_Copy(&m2, &m1);
		if (MTRX_Invert(&m2, 0)) // will use heap for temp storage
			MTRX_Multiply(&m3, &m1, &m2);
		MTRX_Destroy(&m1);
		MTRX_Destroy(&m2);
		MTRX_Destroy(&m3);
	}
	return 0;
}
 

The library is pretty smart about using the allocations. In other words, if you create matrices, and give them enough size, they should never be allocated on the heap; however, if built right, the library will yank space from the heap when needed. To turn off heap allocation, build with MTRX_NO_MALLOC_.

Additionally, the return values from most functions are bool's. This means two things, most functions can fail (generally if the matrices aren't big enough), and you need C9X to build it. Also, a few minor notes:

  • Don't use the inplace transpose function if you can help it. It's quite expensive.
  • The inversion routine requires a temporary buffer. Read the header file for size requirements. (If no buffer is passed, and the library is compiled with heap support, one is allocated.)

As usual this library is MIT licensed, but I'd appreciate it if people would drop me a line if they use it.

A line in the sand

The other day, someone (who shall remain nameless to protect their identity) asked me the following:

I have a set of data points, (X,Y), and I know they are related through a simple function:

Linear Equation

How do I determine m, and b?

Now, there are many ways to determine values for m and b; but, right now I'd like to discuss Least Sqaures fitting.

The original idea for least squares fitting came from Carl Gauss, and it stems from the idea that we'd like to minimize a measurement of the error in our result. In other words, we'd like to find m and b such that error is minimized, or as close to 0 as we can get:

Error Equation

Now, it turns out, minimizing the above function doesn't work really well. In particular, we could pick a and b such that the error is Error Equation, and that wouldn't leave us with a good valu