Tuesday, December 29, 2009

Back to Basics: Square Root Implementation in Python

Two days ago a friend of mine who is a computer science student asked me about the simplest square root algorithm that I know about. Well, I know how pesky students suffer when trying to computer square roots, so I had to choose an easy one.






I know about the famous Cramack method but this sounds complicated to me (though it's the most efficient method AFAIK). So I preferred the goody (Guess, Evaluate, Improve) method. So for example if I want to calculate the square root of the number let's say, 2, my strategy will be like the following: 


1- Pick a guess (1 for example)
2- Evaluate that guess: is 1 * 1 near enough to 2 (see the bold near enough expression!)
3- If the guess is not near enough, Improve it. 


Note that I didn't use the term "equals" when evaluating the expression, rather I used the term "near enough" and this is because, with numbers that are not full squares (like 2 for example), the square root is going to be a floating point number (square root of 2 = 1.414213562373095). Now if you multiply this number --the square root of 2-- by itself, you should expect to have 2 as an answer. Well, that's not gonna happen, rather you're going to get (2.0000000000000004). This is happening due to the way that computers handle floating point numbers --which is a topic of other series of posts by itself. In this case if you used the term equals (or == operator) when evaluating the guess you will never make it, and your program will not halt. That's why I carefully used the term near enough. Defining what near enough means is your choice now, for certain situations you might consider a number that is less than the square root by 0.1 is near enough or 0.001 or 0.0001, etc. This depends on the level of precision that you need for your specific scenario.


The implementation: 
Here's a python implementation of this algorithm.







## calculates the square root of a positive number
## with the passed in precision
def sqrtWithPrecision(x, precision):
    ## The precision must be greater than zero,
    ## root must be a positive number
    assert(precision > 0, str(precision), 'is not a valid value, it must be a positive integer')
    assert x > 0, 'root can not be a negative number'
    low = 0
    high = max(x, 1)
    counter = 0
    guess= (low + high) /2.0
    while abs (guess ** 2 -x) > precision and counter <= 100:
        if(guess ** 2 < x):
            low = guess
        else:
            high = guess
        guess = (low + high) / 2.0
        counter += 1
    assert counter <= 100, '100 iterations done and no good answer'
    ## printing the number of iterations,
    ## in productive code, you might want to remove the next line
    print 'Num of iterations:', counter, 'Estimate:', guess
    return guess

And here's a c# example:

float sqrtWithPrecision(float x, float precision)
        {
            if (x < 0 || precision <= 0)
                throw new ArgumentException("x, and precission gotta be non negative numbers");
            float low = 0;
            float high = Math.Max(1f, x);
            float guess = (low + high)/2f;
            int counter = 0;
            while( Math.Abs(guess * guess - x) > precision && counter <= 100)
            {
                if (guess * guess < x)
                    low = guess;
                else
                    high = guess;
                guess = (low + high)/2f;
                counter++;
            }
            if(counter > 100)
                throw new Exception("100 iterations done with no good answer");
            Console.WriteLine("Num of Iterations: {0} , estimate: {1}", counter, guess);
            return guess;
        }

What Can You Learn From Us? What Can We Learn From You?

Today I got a very interesting question from one of my Twitter friends splattne. The question was:

Here's how I answered the question:

Wow, that's a big one!
I really like your question, Stefan. This kind of constructive thinking is one of the most important methods we can use to avoid conflicts (which might eventually develop wars, and bad stuff).
I will start by what I think that we can learn from you: 


1- Hardwork:

 yes, we're lazy people. Even for the poorer countries (like mine) people are satisfied by working less and gaining less (less than enough). 

2- Democracy:

 I'm not gonna through a discussion with this because it's very obvious for everyone that democracy in our countries is just a shallow word. I mean, come on, every president is preparing for his son to take his place nowadays. This is happening in Egypt, Libya, Tunisia, and many others. 

3- How to learn and teach: 

Education systems in most (if not all) of the Arabic countries are ridiculously inefficient. Chemistry students here enters the chemistry lab one or two times for the whole semester. 

What can you learn from us: 


1- Socializing:

Around here the social relationships are much much better that there in US and Europe. 

2- Conviction:

 Though poor is everywhere, we are not so obsessive with money! A little can satisfy us. 

3- Harmony: 

Different races live together with harmony and love. I've never heard (in an Arabic community) that some one shot another because of his skin color.

At the end, the thing that can really teach you a lot is the Arabic History. We are a bunch of shallow nations nowadays, our influence on the outer environment is very weak, but once we were a real example of a united, well educated, merciful, and highly organized nation.
Thank you again for asking this question Stefan, and I really hope if my answer helps.


What do you think dear reader? What else can we learn from the Europeans/Americans (the good things)? And what can they learn from us(only the good things)?

FormSpring



ASK ME ANYTHING

Today I came a cross this site. The main idea here is that people can ask each other questions and get them to answer them. It also integrates with a lot of other sites like Twitter, Blogger, etc. There are a lot of my twitter friends on FormSpring.
I think the idea is simple and very appealing. Take a look at it and feel free to ask me anything http://formspring.me/Galilyou

Thursday, December 10, 2009

Pretty Neat Extensions For Google Chrome

Today I took a quick whirl to look at some of the avilable extensions for Google Chrome.  And here are some of those that I find interesting:



  1. Wave Notifier : As the name implies it's a notification plugin for Google Wave. Wave Notifier let's you know if you have any new waves or replies and display a counting number holding the number of the new waves. You don't have to keep your wave page open and switch to it every minute or so to see if you get a new wave, or if x of your friends replied to a wave you sent to them. 
  2. Xmarks Bookmark Sync: A bookmarks plugin that synchronizes your bookmarks to Xmarks. You just login using your Xmarks account (or register if you don't already have one) and then you can click the Xmarks button and then click Sync Now.
  3. Google Translate: Translate any web page using Google Translator just for one click. 
  4. Blog This: This is actually a cool one --still overwhelmingly buggy though. It lets you post to your blogger blog from any webpage. 
  5. Google Mail Checker: A notification for Gmail that let's you know whenever you get new emails.
  6. Google Reader Notifier: Notifies you with your new Google Reader items.
  7. Google Calendar Notifier: Same as the two above, it notifies you with your calendar events.
  8. Doc Viewer: Automatically views PDF/PPT documents using Google Docs Viewer.
  9. IE Tab: Yes, it's an Internet Explorer tab inside Google Chrome! 
  10. Speed Tracer: This one is actually the rock star of all of these extensions (at least  for me). You enable it, and then it goes and analyze the processing of a web page that you are requesting. It displays very useful graphs and charts that are extremely helpful for you as a developer to inspect and discover areas of improvements in your web site. More on the very thing later, stay tuned!
Those were some of the many extensions available now for Google Chrome. Go ahead and take a look at the official extensions page from Google here.

Those were some of what I liked, what do you like dear reader?

Sunday, December 6, 2009

Which Isolation Framework?

In the world of unit testing Isolation Frameworks are everywhere. Isolation Frameworks are very handy tools to help you create mock objects. According to Wikipedia:
“mock objects are simulated objects that mimic the behavior of real objects in controlled ways”




In the world of .NET there are a lot of tools out there to be used as Isolation Frameworks. There have been a lot of debate around the best isolation framework –Including this StackOverflow question.
If you have used any mocking framework, and felt like it’s a good tool to use, please vote on the poll on the left to this post or leave a comment about your experience with your preferred isolation framework.