Jospehus Interactive

If you’re into math puzzles, you have probably come across the Josephus Problem at some point or another. If you enjoyed testing your ability at finding the right spot, there’s an interactive version (the theme slightly mangled with creative licence). Enjoy!

Continue reading » · Rating: · Written on: 07-28-10 · No Comments »

To The Power Of, by hand

I’ve often needed to create a power function, as in 2^3 or more commonly Math.pow(2,3) = 8. However, sometimes, the Math.pow() doesn’t exist and the operator ^ is reserved for other useful functions or not recognised at all. In times like that, you need to hand roll- so here’s a good link to keep bookmarked.

Continue reading » · Rating: · Written on: 01-08-10 · No Comments »

Playground Update

The playground has got a new update: stats-related. We covered the sections where you can uncover a bunch of numerical descriptions on a dataset, which is useful for a quick overall summary of the data. I’ve used this tool a couple of times myself preparing for exams and checking manual calculations (yes, sometimes i need to do this type of thing manually) and of course, it’s much easier than using my Sharp or Casio calculator.
And then there are times when you need to examine the relationship between two variables…

The “Applied” Stats Calculator helps with that quite a bit by giving you a fairly (or so i’d like to think) easy way of inputting your data and then calculating and displaying the relationship through a least-squares attempt on the data provided. There are two motivations for this development:
a) linear relationships are more meaningful than just describing a dataset on its own
b) a showcase in extending the javascript library, complete, as always, with tests.

statsbi

Continue reading » · Rating: · Written on: 06-09-09 · No Comments »

Golden Section Search

For me, implementing code really helps me to understand the algorithms (i need to know) better. It might sound a bit odd in that you might need to understand the algorithm before you can implement it. And that’s partially true. An understanding is definitely required. But, with TDD and iterative processes ingrained, discovery of what makes the algorithm tick is made possible through doing it (by repetition and/or implementation).

Repetition helps you to understand it and use it. Implementing it in code is like rediscovering the algorithm from the beginning. It’s a small taste of that journey- and it’s addictive :) Anyhooo, the Golden Section Search is not an exception- but surprisingly trivial. Maybe it was just all the fluff around the topic that got me distracted….

class Golden
  ...
  def search(tolerance)
    return if(@b - @a) <= tolerance

    dif =R*(@b-@a)
    x1 = @b - dif
    x2 = @a + dif
    vx1 = i_eval(x1)
    vx2 = i_eval(x2)

    if(vx1 > vx2)
      @b = x2
    else
      @a = x1
    end

    search(tolerance)
  end
  ...
end

“i_eval” just evaluates the formula you supply (and uses the built-in Ruby expression evaluation) but the part that makes the grok for me is the if(vx1 > vx2) bit.

The way the text books explain it is pretty long-winded. The interval of uncertainty changes, but you’ve got the unknowns a,b,x1 and x2 floating around and changing positions all the time during the explanation. Plus you’ve got to now try remember case 1, case 2 and case 3. Eish. And all that inter-mixed with function and set notation. But that can be maths for you: pick any number between 0 and 10 => pick any integer from the domain of real numbers over the interval from, and including 0 to, and including 10.

The short of it lies in… :

‘b’ changes to x2 if vx2 [or f(x2)] is smaller (or equal) and
‘a’ changes to x1 if vx1 [or f(x1)] is smaller ..

… for the next iteration, everything else keeps the same value. That’s it.

And graphically, it also makes more sense to simplify that for one second and draw the lines in and see how ‘a’ and ‘b’ move along the axis iteration after iteration. Once that’s settled, going back to the ever pedantic yet accurate language of maths is then a whole bunch easier.

Continue reading » · Rating: · Written on: 05-29-09 · No Comments »

Refinancing Model

While explaining Morty, I left with a parting shot: Be careful about consolidating your debt. And before I continue, i will make the disclaimer that I’m not a financial advisor, just a curious number cruncher. So not entirely satisfied about not giving an example, I’ve now had the time to consider the model more carefully to present you with some numbers. So here goes…

Scenario: 2 loans exist, one for a house taken out in May 2004 for 800K at 14%, and one for a car in May 2006 for 160K at 16%. Come May 2009, you decide to consolidate your debt (for whatever reason).  Note, I will purposefully line up the dates and use nice round numbers to get the point across. Also, the interest rates used reasonably reflect the situation in South Africa at the time (as my memory serves).  But regardless of the actual numbers, the same maths (and hence lessons) apply. The math follows:

Home Loan:

  • 800K at 14% over 20 years = 9.9K repayment
  • You will end up paying 2.4M for the house over 20 years
  • That’s 1.6M in interest alone
  • After 5 years, you have paid off 600K, but have only 54K in equity

Car Loan:

  • 160K at 16% over 5 years = 3.8K repayment
  • You will end up paying 230K for the car over 5 years
  • That’s 73K in interest alone
  • After 3 years, you have paid off 140K, but only have 83K in equity

Now you want to consolidate your outstanding debt under one loan. And, we’ll assume you’re refinancing under more favourable interest rates- else why would you even reconsider it? So what you actually owe at this stage will be the sum of the settlement values on each loan, which will largely depend on the agreements you have in place. Let’s assume everyone plays nice and they let you off with the original loan less your current equity. It could be a lot worse! You now owe a total of approx 840K which you need to refinance, and because one of them is a house, you might end up reasonably re-mortgaging over 20 years again:

New Loan:

  • 840K at 11% over 20 years = 9.2K repayment
  • You will end up paying 2.2M for the combined loan over 20 years
  • That’s 1.4M in interest alone

So, where do you stand at this point?

You’ve definitely made a short-term saving in terms of your monthly repayments (10+4 vs 9). Your cash flow is a lot smoother! But with 2 seperate loans though, you would have paid a grand total of 2.6M (2.4M + 230k) over the lifetime of those loans. With a consolidated loan, you would have paid a grand total of 2.9M (2.2M for new loan plus payments already made on previous loans of 740K). Plus, your cash flow potentially deteriorates over the medium term. Once the car loan would have matured, you’re paying almost the same repayment (especially if by this time the interest rates have dropped) anyway. And then in the long term, you’ve got an extra 5 years of repayments to cover which is worth 0.5M of cash flow in the future.

All, in all, the simple summary of it that is you end up losing approximately 300K in the long run.

But it’s not all that bad- it can actually be to your advantage too. If the difference between the original financing rates and the new financing rates are large enough, you can actually save yourself a lot of money in the short, medium and long term too. But that requires approximately a 5% difference _at least_.

So think twice before you jump fall for the debt consolidation marketing trap. Make sure whoever is advising and structuring it for you that they go through all the numbers and look at it long-term. Obviously the refinancing will always benefit the lender which is expected and acknowledged, but just how much is fair and reasonable? We all have the right to make informed choices- and we should insist on that right- and just because it might sound technical or complicated or involve a lot of numbers, doesn’t mean it can’t be explained in a way that makes sense to you.

Hope that helps to at least think a little more deeply about the choices out there….

Continue reading » · Rating: · Written on: 05-22-09 · 3 Comments »

Pizza And Maths

Most of the time, when i talk about maths to anyone, i hear the same chat:
Maths is hard
You either get it or you don’t
Maths is not for everyone
Rather you than me
Oooo. Maths. Eish.

And so on… Well, maybe true but maybe not true at all. Regardless of how you feel about it, there are times when it’s very practical, almost *fun*, to know just a little about it. And you don’t need first year university maths to work some things out.

Butlers Pizza (arguably the best pizza in Cape Town) have a deal where you can buy 2 large pizzas or get a 3 for the price of 2- for roughly the same price if you get 3 mediums. Which is more pizza? Which is better value for money? And more serious questions like: how much cold pizza will i have left over for lunch/breakfast tomorrow?

A medium is 26cm, a large, 32cm in diameter. Assuming the bases and toppings are all mostly equal, you can simplify your calculations to work on the surface area of pizza presented. And given pizzas are more or less round, you use the formula for the area of a circle (π r2). Once you’ve established the area for a medium, multiply the result by 3 to get a combined pizza surface area. For the larges, repeat the exercise and multiply by 2.

You can judge at this stage which deal is going to give you more pizza. But what about best value? Well, take the total amount of pizza and divide it by the cost. Your answer is pizza/rand. So go for the deal that has the highest number. So the “Big Deal” will cost you 98.95, the 3 pizzas will cost you 2×49.95 (assuming simplest case) . You should know pretty soon which you want: more pizza or best value for money?

Of course, it gets so-called “complicated” when you start adding extra toppings and wheat-free bases. But all those “complications” are just little additions to the same steps. It’s actually not complicated at all- it’s methodical. And all the information is there, you just need a simple calculator.

Of course, some might say: why bother? Indeed. Why bother at all? Well, why not? It’ll take you less than 5 minutes to arrive at an answer which maximises your utility- which is economic speak for: get the best bang for buck. And especially when it’s close to the end of the month. But there’s also a deeper truth which you start to uncover… just how “special” is a special really? And even more grave, what’s breakfast going to be like?

Continue reading » · Rating: · Written on: 02-20-09 · 1 Comment »

Put It In the Bond?

If you’re servicing a mortgage at the moment, and you happen to come into some money, the “best” advice you’re probably going to get is: “put it in your bond”. Not bad advice, i guess, but i’m not so sure it’s the “best”.

**DISCLAIMER: I’m NOT a financial advisor; am not pretending to be one; and certainly not qualified to be one. But i can kinda do the numbers, so this looking at it purely from a mathematical perspective.

When it’s not really the “best” advice is when you are servicing other debt, at higher interest rates. Then the numbers say: kill that debt first, and _then_ look at the mortgage. So if you’re servicing a credit card, overdraft or vehicle finance (which can typically be higher than prime) and your mortgage is sub-prime, service the higher first.

But more personally, i recently faced the opportunity of trading in my vehicle for a newer one (which would have been nice) and i was figuring out what to do with the trade-in amount and work out where it would best pay dividends. On an aside, i’m of the opinion that buying a vehicle is NOT a financially smart move at all- no matter how you try slice the numbers. You will always lose (and i’m not referring to collectors’ classics). So look after your car- treat it nice, drive nice, service it regularly so you can leave it in your will. After all, it’s __just__ a car, right ;)

So down to the maths… Note: the numbers have been changed slightly to protect the prudent.
New car: R150k at 15.5% APR over 60 months.
Existing debt: R640k mortgage (±30 months into the schedule) at 14% APR over 20 years.
Trade in on car: R50k. What to do with the R50k? A) Plough it into the bond. B) Use 100% of it as a down payment on new car. A or B, what do you do? The “best” advice i received was plough into the bond and save thousands in interest on the bond! Uhuh. That’s half the truth.

As a down payment on the new car, I reduce the repayments from R3.6K to R2.4K, and end up saving, in effect, R44k in interest over the term. Not bad, not great.
In the bond, i reduce the interest _over the same term_ by R33K. Worse. But not a surprise. And that’s the important part here: the same term. 60 months. You see, over the remainder term of the mortgage, that advance payment will save you A LOT! But now you’re comparing a value of money of two different terms: 60 months versus N years on the mortgage, so don’t be too surprised if you draw bogus conclusions. Afterall, once you’ve finished paying off the car, you’re R3.6k deeper in the pocket which you can then plough into the mortgage anyway.

So, on face value, it’s more favourable, over the same term, to service the vehicle as quick as possible and then see to the lower interest obligations. But there are better options… which is the other half of the truth: discipline.

Add in some fiscal discipline into the mix, and suddenly your options are wild. For example…

Put down the down payment on the car, saving an extra R1.2k in repayments each month on the car, but then put the saving into the mortgage over the same term. Suddenly you start to save R64K in interest. Mmmm… Or…

And then there’s this. Which really was the best option (Thanks, A)…

Take your old car for a shmancy valet at about R200, pretend it’s new and “pay for it” anyway at R3.6k per month. Now you’re saving close to double your previous best!

The bottom line is; if you’re in the market for a car and can afford X, but you’re servicing other debt, service that debt first- forget about the car*. Unless it’s an absolutely necessity (and looking better than the Jones’ is not a necessity- i checked) you probably don’t need it.

*Forgetting about the car, probably anywhere in the world, is really hard to do though. In South Africa, households spend a disproportionate amount of their disposable income on vehicle financing, which says a lot about how we feel about our cars. Somehow, cars have so (too) much appeal. So much so that having 4 reliable wheels is just never enough. There’s always going to be something really “cool” about a car that makes you just wanna have it. And the price tag is just irritating. Can you say X-Trail… or Fortuner? :)

Continue reading » · Rating: · Written on: 11-02-08 · No Comments »

BSc. Year One

Study unit

Description

Mark

Result

  APM113U APPLIED LINEAR ALGEBRA 91 Passed
  MAT103N LINEAR ALGEBRA 75 Passed
  MAT110M PRECALCULUS MATHEMATICS 68 Passed
  MAT111N PRECALCULUS MATHEMATICS B 70 Passed
  MAT112P CALCULUS A 59 Passed
  MAT113Q CALCULUS B 58 Passed
  STS1055 BASIC STATISTICS 56 Passed
Continue reading » · Rating: · Written on: 02-21-08 · No Comments »

MATLAB R14sp3 On Ubuntu 7.04

A couple of things to be aware of if you’re doing this installation, which i discovered through trial and error :)

The machine id used for activation is based on the MAC address of eth0. On my machine, for example, my active interface is primarily the wireless card which is set as eth1. Hence, no machine id available for activation. How to fix?

bryan@noah:~$ cat /etc/iftab
# This file assigns persistent names to network interfaces.
# See iftab(5) for syntax.

eth1 mac 00:00:00:00:00:00 arp 1
eth0 mac 11:11:11:11:11:11 arp 1

where 00:00… and 11:11… represent your actual MAC addresses obtained by ifconfig.

My wireless card was eth1, so i simply switched this around so that my wireless is now eth0, rebooted and i now have a machine id with which to activate MATLAB.

Second issue was an error to the tune of: “version GLIBC_2.0 not defined in file libc.so.6″ when trying to use the Symbolic Toolkit, particularly. See the MathWorks Technical Solution for more information on this error. The steps they outline there didn’t work for me (it is for Red Hat afterall), but what did work was copying the libmaple.so (provided by MathWorks) into your matlab/glnx/bin directory. See discussion here (in German).

Success. Incidentally, i’m using MATLAB because my university wants me to use it, but otherwise if you need something equivalent in the OSS sphere, try Octave. ;)

Continue reading » · Rating: · Written on: 06-04-07 · No Comments »

Fractions and Foating-Points

Floating-point arithmetic on a computer is hazardous, at best. This post is not a detail description of the problem. Varied descriptions of the problem already abound, like this one, for example. There’s also documented pain out there to understand that it’s not just your computer :) No, this post is just one way of getting around the problem in a particular context.

The environment: JavaScript. The problem: convert decimals to fractions and fractions to decimals. Getting a decimal is straightforward:

function fractiontodecimal( wholenumber, numerator, denominator ) {
wholenumber = parseFloat(wholenumber);
numerator = parseFloat(numerator);
denominator = parseFloat(denominator);
return ( ( ( wholenumber * denominator ) + numerator) / denominator );
}

Obtaining a fraction was slightly more insane since in JavaScript
23.8 * 10 = 238
but
23.88 * 10 = 238.79999999999998

Not exactly what you need to work with. As you can imagine, inside a loop of sorts, and if the number becomes very small and you divide by it, you start getting bigger errors. Anyways, that’s a digression in itself. What i needed was a reliable way to multiple by a float by an integer, 10, and get a predictable response. In other words, i just needed to keep shifting the decimal point. Most immediate response might be: string manipulation. Isn’t that what JavaScript is for? :p

Another way was using e-notation. 23.88 being represented as 23.88e0. Multiply by 10: 23.88e1, and so on. The good news is you still get to do a little string manipulation, but not nearly as hectic as finding and moving a “.”

The particularly heavy looking string manipulation looking like:

newDecimal = mantissa + “e” + exponent;
That wasn’t so hard, now was it? :D

Browse through the code for decimal.htm (HTLM page with JavaScript)

Continue reading » · Rating: · Written on: 05-22-07 · No Comments »