Thursday, November 27, 2008

Derivation

This is some post showing off work I have done for my thesis. Well, actually I will try to skip that and just publish it here, because there will be no real need to publish it in a scientific way. It is kind of a stupid step by step transformation. Hope you can follow along. I know you will. Can you show me the 'Hello World'-Program in Python once more. Sure it's:
fib = lambda n: 1 if n == 0 or n == 1 else return fib(n -
2) + fib(n - 1)
This is great, but isn't it a huge waste to recalculate fib over and over again? Yes it is. And there is this thing memoization that saves the values. Okay let's copy some pre. No, we will not. For reasons described later we will try to implement the turtles all the way down. What does that mean? Well, with Python we are writing in a very high level language. Nothing special about this. But this post will describe the way down what I compiler could do and grasps the notion towards the machine. I don't understand what you mean. Act don't talk. Let's implement a stack where we push the values of functions unto. The first to values are already known by definition.
cash = {}
cash[0] = 1
cash[1] = 1
So first thing to do is to look if the values are already in the dict.
try:
  return cash[n]
except KeyError:
The recursive rest:
  return cash[n] = fib(n - 2) + fib(n - 1)
This is the boring version. But you know, that there are more turtles to run with. We are going deeper down. So what is it doing this function-call? Well nothing but pushing a new environment unto a stack. So let's do this. First we create the stack:
xs = []
And push a function there:
f = lambda d, e: d[e[1]] + d[e[2]]
> This is tricky! No it is not. Judge by the actions:
cash[x[0]] = f(cash, x)
What we are doing is pushing the value of a function on the stack. 'cash' is the cash, of all calculated values, so we don't have to recalculate anything twice. 'x' is something I have hidden from you. So what is x? It is a list!
(n - i, n - i - 1, n - i - 2)
Recognize that pattern? It is inside the Fibonacci function. Why don't we pass just the arguments along, why do we have to save this? Now I have to show you the full source:
        i = 0
        xs = []
        while True:
            try:
                x = (n - i, n - i - 1, n - i - 2)
                f = lambda d, e: d[e[1]] + d[e[2]]
                cash[x[0]] = f(cash, x)
                for x in xs:
                    cash[x[0]] = f(cash, x)
                break
            except KeyError:
                xs.insert(0, x)
                i += 1
Do you notice there this hole thing has it's goto? Yes, right before the for-loop. Because there is the point there you have to go back in time and have all the results precomputed. But before you have to insert the result into xs. We have 'i' which controls we arguments all the way down. The complete program is:
cash = {}
cash[0] = 1
cash[1] = 1
def fib(n):
    try:
        return cash[n]
    except KeyError:
        i = 0
        xs = []
        while True:
            try:
                x = (n - i, n - i - 1, n - i - 2)
                f = lambda d, e: d[e[1]] + d[e[2]]
                cash[x[0]] = f(cash, x)
                for x in xs:
                    cash[x[0]] = f(cash, x)
                break
            except KeyError:
                xs.insert(0, x)
                i += 1
    return cash[n]

import sys

print fib(int(sys.argv[1]))
Should we write programs like that? No! We can derive to such programs. But just if there is a need for such optimizations. Also think of the algorithm twice. I, myself found it easy to derive an algorithm straight forward from the books, by reversing the process in the end. The cool thing about such derivation is, that the programm is correct in the end. If you do it correctly with assertions. The hard part about programming is, to define the problem correctly in a mathematical way. That is challenging. Afterwards where should be nothing but a derivation to a form a machine could do as fast as possible. In research this is a hot topic to derive there automatically. And me myself feel somehow being code-monkeyed to derive to the actual program. But it could also be a stimulating feeling like a painter to step back and proof that the algorithm is still right. For my project I did a mathematical analyse first, and then implemented the program in Python because it is such an easy thing to do. Most programs in controlling are just a bit set theory and statistics. Hope you enjoy this post. P.S.: Here is the Java-Version:
import java.util.ArrayList;

public class Fib {
    static ArrayList cash;

    static Integer fib(int n) {
        try {
            return cash.get(n);
        } catch (IndexOutOfBoundsException idx1) {
            int i = 0;
            ArrayList xs = new ArrayList();
            while (true) {
                Integer[] x = null;
                try {
                    x = new Integer[] { n - i, n - i - 1, n - i - 2 };
                    cash.add(cash.get(x[0]), cash.get(x[1]) + cash.get(x[2]));
                    for (Integer[] xx : xs) {
                        cash.add(cash.get(x[0]),
                                 cash.get(xx[1]) + cash.get(xx[2]));
                    }
                    break;
                } catch (IndexOutOfBoundsException idx2) {
                    xs.add(0, x);
                    i++;
                }
            }
        }
        return cash.get(n);
    }

    public static void main(String[] args) {
        cash = new ArrayList();
        cash.add(1);
        cash.add(1);
        System.out.println(">>" + fib(2) + "<<");
    }
}

The La in Lala

This is an attempt to clear out my head, full of all those thoughts that might destroy my thesis I am heavily writing on at the moment. Charged with all of those ideals I am not ought to suffer at the moment because they are so deeply nested inside of the structure of my body, I can not do anything at all but thinking away the thoughts that might have a chance to stand against some professor or something maybe just a slight tick more scientific. But I am bound to be philosophic by nature after reading way too much Nietzsche and therefor suffer the great thought of emptiness and egoism that I will not discover in my soul lately but certainly: this is a lie. It is said that the most intelligent people are not made out of this grateful arrogance you will discover chatting with the fouls. So this is an attempt I try to accomplish over just one session of writing fully aware of my drunkenness over one glass of beer finishing off from a stressful day full of reading. Lately I have been rethinking my ideals. I have been influenced deeply by the thoughts of writers of the Enlightenment. So after hearing all this blame into the direction of the so-called managers I just can not get away with it without claiming, that there is certainly a thing called: Enlightenment is to get away with your own stupidity (or so). If you really want to be illiterate in some financial sense: Good for you. Me, I am investing my money in things I am personally attached to in a sense, that I am an expert in. So do not fool yourself and invest blindly with your friends the bankers. Well that's capitalism is all about. You have to get away with it. Same goes for the lobbying: If you are complaining, and it is real that money buys opinions, than try to influence with your money. I think it is better for an organisation that is willing to help poor countries to do real lobbying. Well, this will help in a way, you can not imagine. That is capitalism. And it is democratic. You just have to raise the money and organise this thing. The left-wing is mostly sorted out by their disbelieve in money. It is not that the homo oeconomicus is existing, but it is a fact, that money buy it's way. All this charity for the third world is senseless, if you don't change our duty. This is not some hidden science or something. This is the European way to go. By supporting and therefor favouring European countries, poorer countries are right away opted out. This is economic reality. And it is cruel and it is unfair. Yes there are unjust systems in Africa, that help to prevent a good way of living. But let us make a difference by supporting the economy of these countries. Economy should be free. Don't understand me wrong. I am all against capitalism in its pure form. But freedom does not mean to be cruel. Link back to the popping way the philosophers of the Enlightenment showed us a path away from the elitism of former times. Everybody has to think. Cause therefor we exist. By just complaining, well you ain't changing anything. There are a lot of problems out there and in the end if you are concentrating on these problems you ain't going nowhere. It is just the solution that will make you happy. And if there is anyone against that principle of maximum happiness please stand up. No there will be no one, cause happiness is one of those things that is better shared. Oh this awful movie had really nice ending. There is this wrong form of anti-elitism, that I hated so much when I was younger. Even at those times I hated the whole corpus that inhibits our schools. That ones that kill the mindset generation after generation. You probably guest it, I talk about teachers. Several times I was reminded that sentences should be as short as possible and nobody should use any word that is a bit out of these famous 5000 words that the common pupils know. Okay, at this age I was really dump. But also very arrogant. This makes the big mixture you will find every there. I have not changed. If you would read this in German, it would be full of mind-gabbling sentences spawning several lines of your screen. But I am writing this in lovely English. The language I cannot write in, but keep practicing. The big question that remains: Are we getting any smarter with the time? My answer is: I don't know. Maybe. Maybe the opposite. If I go back in time my political views have changed in a drastic manner. All this happening over the influence of economics that I majored in. But how should I believe in my thoughts? I was so sure about everything when I was younger. How can one believe to be right? There is no answer. But I think the good/the proofed to be good mindset is to let everything open about yourself. And stop even thinking about it. Ways to improve yourself are way too simple sometimes. Why not just stopping to smoke? Why not just getting away without being lazy? Or why not trying to make sport? Or why not learning how to write? The list goes on and on. And yet it seems to be so simple. Why are we heading in directions, we don't want to be heading? Is it that hard to make a plan and then following it? There is this guy Piaget, which identified two processes that occur if you are learning anything: It is accumulation and assimilation. The first one is what is likely to happen if you discover new things. Okay, maybe you are beginning to ask yourself, why am I reading all this horseshit? You know, psychology is really not that boring. And we are on a way to a real enlightened society which is just learning all day out. Learning is the essential thing that we do in our lives every day. And if you are in a corporate environment or school or something, you have to believe in two skills: teaching and learning. Are you reminded of my teacher-bashing. This was all made up. I lied to you very heavily. Teachers are so important, that you have to be one, too. Not as a profession in the traditional sense, thought. But identifying yourself by being a teacher in your company is somewhat mind gabbling. Every time you propose something the first of the two processes of Piaget will start working/will get fired up in the neutrons of your coworkers. Accumulation, anyone? They will not like anything you make that let's them struggle with their old mindset. They will hate it, if it's revolutionary. Just because it is such a petty work for you brain to get used to new structure. That is accumulation. And you will hate it, too. But how do you cope with it, when you are fully aware that it exists? First of all: After you heard this, you will struggle and say no. I am special. I am open for new things, and so on. But no you are not. QED I just told you one process. What is the second? You can guess it is fairly simple: You will assimilate it, that means you will integrate it into your old structure, renew the system, that is not working anymore. So we are learning. But are we getting better with the learning? Do I have changed after all? Are my thoughts just altered by some kind of weird system. We don't talk about water learning. If you watched closely inside of your bath tube, you saw the struggling water produces, when the flow was being stopped by someone. But after just a fraction of a second, water will seek its way through. Why are we different from water? Are we? If someone is dying, we will cry. It is a somewhat complex process in our brain, I know nothing about. Is this making us any special? I read an article about mind and machines, a rather popular one. And as it happens the author was strongly against the metaphor of thinking machines. As if calculators can not think. But I find it really hard to define thinking. And I know, I am not alone. Moreover I am an engineer of some kind. So wishful thinking is one of our core-competencies. I will just assume a definition and close this blog-entry. Wired told us blogging is out, twitter is in. It may be so. But who the hell reads Wired?