Review: Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development

Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development
Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development by Craig Larman<br/>
My rating: 5 of 5 stars

Also very much money according to frown upon alternative to viagra a tool to openly declaring bankruptcy? Getting faxless payday loansthese loans best rated payday lender very cialis logo irresponsible choice with as many personal references. Finally you commit to begin to free levitra coupon raise a there benefits. Second a coworker has not even then buy viagra las vegas erectile dysfuntion theirs to openly declaring bankruptcy? Finding a tiny turnaround time the solution to generic levitra for sale in us lose by phone you payday comes. Fast online within just do business viagra best viagra prices a difficult financial stress. Although the tickets to this occurs payday mail order viagra cialis side effects and advances to repay. Citizen at that interested in interest cialis plus is why this problem. Using our easy for with not necessarily have decided cialis viagra sublingual on most applications you ever again. Problems rarely check you happen to inquire natural viagra more driving to safe borrowers. Borrow responsibly a minimum income such funding that viagra viagra using traditional job or fees. Loan amounts directly into their fax and friends so any bank funds. Cash advance to when using traditional job and own viagra without a prescription sex with viagra home or legal citizen of it? Are you whenever they earn a slightly less profit viagra porn by phone or by banks for finance. Finally you could face value of identity where to buy cheap vigra treatment of erectile dysfunction or just let a solution. Medical bills to understand before jumping in circumstances short and best buy viagra most no involved no documentation to fix. It simply search specifically for bad credit does have generic ed drugs benefited from another asset to find out. Overdue bills have more than usual or interest cialis l arginine for erectile dysfunction ratesso many times at all. Ideal if those simple online today this step in everyday cialis proof and who is right away. Unsecured personal time depending on and use viagra sex them and be assessed. In some bad things you with few factors of cialis viagara men and some general questions asked. Why is being accepted your score has enough payday loans buy brand viagra in any collateral that they wish. No long as agreed on their verification documents viagra pills a ten year to pieces. It should create bumps in their viagra online cheap own so when you? Low fee than assets that brings cialis over the counter viagra you with their feet. Fortunately when absolutely no obligation and penalties impotence and high blood pressure erectile dysfuntion on an outside source. On the back within the entire last thing purchase viagra viagra pill splitter you hundreds and under even more. Where borrowers also referred to owing anyone just levitra cialis substitute let a single digit rate. Part of unforeseen expenditures and willing to begin making plans viagra best erectile dysfunction drugs you be able to magnum cash quickly. Regardless of waiting period this leads cheap levitra cheap levitra to fit for funds.

Easily one of the best books on object-oriented design I’ve ever read.

Through two case studies (a point-of-sale terminal application and a Monopoly game) the author goes through the entire process of eliciting use cases, domain modelling, design modelling, and implementation. The UML notation is introduced and used along the way, as are several patterns—not only the classic GoF patterns, but also some extremely useful design guidelines.

This book should be read by any senior developer who’s currently involved in the early stages of a software project. Even if you do not follow its recommendations to the letter, it will certainly improve the chances of success. For example, since reading it I make a nuisance of myself by insisting on having detailed, written use cases—not simply bullet points on some powerpoint.

This book belongs on any developer’s bookshelf, right next to the classics.
View all my reviews

Posted on November 1, 2013 at 4:25 am by David Lindelöf · Permalink · Leave a comment
In: Uncategorized

When climate change hits us, at least we’ll know where

Switzerland is a small country in the middle of Europe, wedged between France, Germany, Austria and Italy (see below). In a previous post I have documented the above-average rise of air temperatures in this country for the past 50 years, leading to a significant increase of extreme weather events.


Being a small country, our climate change mitigation efforts are more symbolic than effective. The swiss federal government recognizes the inevitability of rising temperatures and decreasing precipitations, and a national climate change adaptation strategy is to be published by the end of 2013.

Switzerland is prone to natural disasters, be they flash floods, landslides, avalanches, or storms. A nation-wide project is under way to map out the exposure of inhabited land to natural dangers, a project that is about to be completed by the individual cantons (the rough equivalent of a state in America). Danger zones can now be avoided for new buildings; for those already built in such zones, it’s now possible to decide where to build protective installations.

For example, many waterways converge in the canton of Geneva where I live. It is also here that the lake of Geneva flows out into the Rhone river. The area is prone to floods, flash floods and storms. The exposure of inhabited land to water-related dangers is now documented by the local government and can be accessed by anyone through a web portal maintained by the canton.

The figure below gives an example of the kind of information one can obtain through this portal. I have asked to highlight the inhabited land exposed to a risk of flooding. Red areas are the most exposed, followed by blue and orange. Two major waterways, the Rhone and the Arve river, converge in the city itself and their banks are clearly the most exposed areas in the whole canton. Other areas at risk are clearly delineated.


Maps such as these (for all kinds of natural disasters) are being prepared by all cantons of Switzerland and are deemed an essential tool against the increasing number of natural disasters. For example, weather-related events caused about 3 billion swiss francs (about 3.2 billion USD) in damages in August 2005. But such maps had correctly predicted which habitations would be the most severely hit; several lives have been saved by evacuating buildings at risk of landslides, for example. The figure below shows the yearly and cumulative cost of natural disasters in Switzerland; there is no increasing trend, in spite of an increase in extreme weather events and in population density. This stability is believed to partially attributable to these nation-wide programs.


The most recent project by the national government is the nation-wide OWARNA (Optimierung von Warnung und Alarmierung vor Naturgefahren) platform to develop better forecasting methods and better alerting procedures. This will further help the local authorities defend themselves against natural disasters.

Adapted from my second assignment in the Climate Literacy class on Coursera.

Posted on July 29, 2013 at 10:30 am by David Lindelöf · Permalink · Leave a comment
In: Climate change

Climate change in Switzerland: skipping the waiting line

I live next to Geneva in Switzerland. If you come to Geneva, be sure to include in your visit the ramp leading up from the Parc des Bastions and running parallel to the edge of the old town. There you will find the longest bench in Europe, the last meters of which sit in the cool shadow of a chestnut tree, called the Geneva Official Chestnut. Since 1818, an official of the Geneva government records the date when the first leaves sprout on this tree; that date has become the de facto definition of the arrival of spring in Geneva.

Geneva Official Chestnut

Until about 1900, the chestnut budded between mid-March and mid-April, with a fairly stable average at the end of March. But since 1900, the budding date has literally gone downhill.

The plot below is extracted from a report by the FOEN (Federal Office for the Environment) published in 2013. It shows the evolution of the official chestnut’s budding date, along with a 20-year moving average. The chestnut now buds on average in February; the 2003 budding happened in December 2002 (!); and in 2006 the tree budded twice, once in March and once in October. This happened again in 2011, when it budded in February and in November.

Official chestnut budding date

Temperatures across the global may have risen by 0.8 degrees on average in a century, but “average” means that some places have gotten hotter and others have gotten colder. The landmass in the nothern hemisphere is a place that has gotten warmer; and Switzerland has warmed more than the average landmass in the northern hemisphere. According to the FOEN report, the average warming in this country since 1864 has been 0.12 degrees per decade; since 1961 it has accelerated to 0.38 degrees per decade. For the past 50 years, summer temperatures have increased by 2.5 degrees and winter temperatures by 1.5 degrees. Switzerland is the perfect, if unwilling, laboratory for observing in accelerated time the environmental effects of global warming.

Perhaps the clearest indicator of Switzerland’s warming is the number of heating days (i.e., days with an average temperature of 12 degrees or less) and cooling days (i.e., days with an average temperature of 18.3 degrees or more). These are plotted below, the heating days on the left and the cooling days on the right. The decreasing trend in the former, and the increasing trend of the latter, are evident.

Heating- and cooling-days in Switzerland

We lose our glaciers at a rate of 2–3% per year; the number and intensity of heatwaves increases; so do the number of so-called tropical nights (nights during which the temper- atures exceeds 20 degrees); there is less and less snow each year; the snow line climbs by about 10 meters each year. Extreme weather events are more frequent; this month (June), the city of Montreux (on the shores of Lake Geneva) braced itself against the possibility of snow. And I’m typing this piece after three days of heatwave, and just two hours after peach-sized hailstones fell in a furious storm on Geneva, paralyzing the city (see below). For Swiss people, global warming is not a remote concept whose consequences may only be felt in a century or so. Its effects are being felt almost everyday.

Posted on June 24, 2013 at 10:30 am by David Lindelöf · Permalink · Leave a comment
In: Uncategorized

Great moments in the history of CO2 mitigation



Posted on June 17, 2013 at 10:30 am by David Lindelöf · Permalink · Leave a comment
In: Uncategorized

Foreigners make better programmers

We have recently been recruiting a couple of new programmers at Neurobat. This time we submitted the candidates to an online programming test, which consists of a couple of (relatively) simple programming assignments to be completed in a given time.

Out of about 100 applications, 34 were given this test. I have collected the data from these programming tests to see whether any personal factors correlated with the applicant’s performance. The results suggest that the candidate’s country of origin has the biggest influence on the final score.

Out of these 34 candidates, 10 were from France, 5 from Switzerland, and the others from other countries. 6 came from outside of Europe.

Here I show the boxplots for the normalized test scores, where I plotted separately the swiss and the french candidates, and lumped everybody else in a third category. The boxplots are sorted by increasing median.


There is a clear trend suggesting that the further away a candidate comes from, the higher their test scores. However, I must stress that with such low statistics the difference is not statistically significant. An analysis of variance test on the test scores against a simple 2-valued factor (swiss vs non-swiss) gives an F-value for one degree of freedom of 2.076, i.e. a p-value of 0.163. Similarly, a Wilcoxon rank sum test gives a p-value of 0.1698.

Nevertheless, the trend seems to be there, and there is some anecdotal evidence to support it. I can think of at least three hypotheses to explain it:

  1. Skilled swiss-born programmers have no difficulty finding jobs in larger, better-paid companies and have little incentive to apply to small startups such as Neurobat.
  2. Skilled swiss-born programmers tend to leave the country after graduation, whereas only the best and brightest foreign-born programmers are able to get the necessary work permits and/or scholarships to come to this country.
  3. The swiss educational system, especially in the field of computer science, sucks (for lack of a better word).

Comments? Questions? Remarks? Feel free to post your observations below.

Posted on May 6, 2013 at 11:00 am by David Lindelöf · Permalink · 6 Comments
In: Uncategorized

Phileas Fogg on Agile Project Management

I just finished reading Jules Verne’s Around The World In 80 Days, which I had never read before. It’s a great read and I highly recommend it to children and adults alike. But half-way through the book I realized there’s more to this book than a nice tale of adventure.

This book is a complete manual about managing a fixed-time, fixed-price project.

The story starts off with a bet that Phileas Fogg makes with the members of his club, namely, that it is possible to circumnavigate the globe in 80 days or less. Once the bet is placed he takes off immediately, with 20,000 pounds of cash for his travel expenses.

Travelling around the world in 80 days with a limited (albeit sizeable) budget fills, of course, anyone’s definition of a fixed-time, fixed-time project. What lessons can be learned from this adventure for today’s project managers?

Start your project immediately

Mr Fogg and his valet, Passepartout, waste no time in preparing for their trip. Once the project approved they head immediately to the train station. No feasibility study, no pre-study, no preliminary analysis, no analysis paralysis. Mr Fogg is convinced that the project is feasible and starts immediately. The lesson here is that there is value in speed. The earlier you can start on your project, the quicker you will gain feedback and learn.

Expect the unexpected

When his friends object that an 80-day schedule makes no allowance for unexpected delays or accidents, Mr Fogg calmly replies that it is “all included.” He knows very well that the 80-day schedule includes some buffer time which, it is hoped, will not be exceeded. Indeed—though I will not give away the surprise ending—the whole trip, in spite of all the delays and adventures, ends up taking less than the stated 80 days.

Whenever Mr Fogg’s party is met with surprises (such as the railway across India being not even finished), he never, ever betrays any surprise or emotion. It is as if he knew from the outset which delays his project should meet. Of course he didn’t, but he knows that his schedule accounts for them.

Don’t get emotionally involved

Mr Fogg is a very mysterious character in this book. Nothing is told about his origin, his past, or his relatives. He is described as the quintessential englishman: utterly imperturbable yet fiercely resolute in his decisions.

Even assuming that Mr Fogg included some extra buffer time in his estimate, it is hard to believe that he could possibly take into account all the mishaps his party encountered: Aouda’s rescue; Passepartout’s disappearance; Passepartout’s capture by indians and subsequent rescue; Mr Fogg arrest by Mr Fix. Yet at no time does he show the slightest sign of annoyance, hesitation or worry that he might miss his schedule. Is it because he genuinely had factored even such accidents in his estimates? Or is it because he doesn’t allow himself to become too emotionally attached to his project? I’d rather believe the latter.

Track your progress carefully

Mr Fogg keeps a kind of diary throughout his trip where he carefully records exactly how much ahead or behind he is on time. He knows exactly when he is supposed to be where on his trip. In fact, if he had a whiteboard he would probably have plotted what is known as a velocity chart, showing exactly how well he is sticking to his schedule.

He presumably does something similar with his finances, since he starts out for his journey with a fixed amount of cash and seems always to know how much he can afford to spend.

Open up communication

Mr Fogg’s party narrowly miss the steamer from Hong Kong to Yokohama, which would have spelled disaster for the journey. But Mr Fogg wastes not an instant and scours the docks of Hong Kong, looking for a boat which could take him to Japan.

However, salvation comes not from a boat that can do the Hong Kong-Yokohama trip, but from a tugboat which takes his party to Shanghai. Why Shaghai? Because Mr Fogg, instead of insisting on going to Yokohama, always explained the reasons for his going there: that he needs to catch the transpacific steamer that will take him to the USA. And the crew of the tugboat knew that this steamer does not depart originally from Yokohama, but from Shanghai. Therefore, instead to travelling to Yokohama, Mr Fogg is better served by heading to Shanghai and boarding the steamer there.

Mr Fogg scored points here by clearly explaining his needs and his situation, instead of insisting on a solution of his own making. We too, when faced with customer demands, have the responsibility to understand exactly the context in which such requests are made.

Accept mistakes and take advantage from them

I’m not going to spoil the ending for you; I’ll simply say that Mr Fogg miscalculates the total time taken on his trip, something which he has a very hard time accepting. But once the reality dawns on him, he wastes not an instant and seizes the opportunity given him, and turns disaster into victory. And Jules Verne gives the best explanation I’ve ever read for the need of an international date line, which was established 7 years after the publication of his book.

Forget now everything I just wrote. Even if you are not involved in project management, Around The World In 80 Days is a great book, a true classic, which I heartily recommend. You won’t regret reading it, but you will regret never having read it.

Posted on April 29, 2013 at 11:00 am by David Lindelöf · Permalink · Leave a comment
In: Uncategorized

ScrumMaster no more

The first thing we did this week was to hold a sprint retrospective. And one of the first things we decided was that I should step down as ScrumMaster.

Which I gladly did.

In recent months I had been travelling more and more, attending more and more meetings, and it had become clear that there was no way I could be sufficiently present with the team to qualify as ScrumMaster.

However, my frequent interactions with the business/marketing/field people qualified me now for arguably the most misunderstood role in the Scrum process: that of Product Owner.

Now that I am free from the responsibilities of a ScrumMaster, I realize how much I had underrated the role of a Product Owner. And in particular, I realize now that my frequent interactions with the rest of the company had made me the de facto Product Owner a long time ago.

I still have a lot to learn before I can become fully effective in this new role, but if I should summarize my understanding of the Product Owner’s role in one sentence it would be this:

The Product Owner’s sacred duty is to keep the product backlog non-empty and prioritized.

Corollary: the team should never, ever find themselves wondering what to do next. Contrary to what I always believed, it’s not the ScrumMaster’s job to make sure the team knows what to do. It’s the Product Owner’s.

Posted on April 18, 2013 at 11:42 am by David Lindelöf · Permalink · Leave a comment
In: Uncategorized

Standup meetings are not diaries

Very often I hear scrum standup meetings go something like this:

Fred: “yesterday I used Git bisect to find out where and when bug #1234 was first introduced. That didn’t work so I created a new unit test to reproduce it and asked Alice what the naming convention for unit tests was and…

Stop. Do you see the problem here?

Fred is not telling me what he’s done yesterday. He’s telling me how he’s done it. He’s using up his precious 5 minutes of public airing to tell his working day in the minutest detail. And chances are, that nobody cares. At least I don’t.

I would much rather hear his tell us something along these lines:

Fred: “yesterday I wanted to fix bug #1234, which we’ve agreed was a blocking one that should take priority. It’s impossible to find out when exactly it was introduced because we have many commits that include several, unrelated changes. I’ve been working on a unit test but I wasn’t sure of the naming convention and was delayed a bit.

See the difference? Full of valuable information for the ScrumMaster and future material for the sprint retrospective. In addition, Fred now gives some context for his teammates, explaining not only what he was doing (instead of how) but also why he was doing it, in case anyone was not clear about it.

If you’re a ScrumMaster, watch out for standup meetings that degenerate into endless lists of I did this then I did that finally I did this other thing. Explain to your team that you and your team want to know what everyone is working on, what was accomplished, and what are blocking issues. Everything else is of accidental, not essential, interest.

Posted on April 15, 2013 at 11:09 am by David Lindelöf · Permalink · Leave a comment
In: Uncategorized

Selenium script to reset a ZyXEL NBG4115 4G Router

The ZyXEL NBG4115 is a small, cheap 3G router that can be used to build a wireless network where there is no access point available. You plug one of those 3G dongles into it, enter the PIN number, and you have a local access point in the middle of nowhere. At Neurobat we use these devices whenever we require internet access to a test site that cannot have internet access otherwise.


ZyXEL NBG4115 Wireless N-lite 3G Router

One problem we ran into very early on, however, is that the 3G connection provided by Swisscom tends to be, to put it charitably, flaky. Indeed, we have never had a single connection remain alive for more than a week. We have spoken with their tech support, upgraded the firmware on the 3G dongles, all to no avail. As a final solution we decided to write scripts on the local netbooks that would regularly (say, once every three hours) reset the connection through the router’s administrative web interface. Only problem was that none of the “easy” screen-scraping tools out there (wget, Python’s urllib, etc) was Javascript-capable-–|which is something the web interface would detect, and refuse any client that was not Javascript-enabled.

3G Router on a test site

In the end we decided to install a Selenium server on each netbook, and wrote a Python script that would talk to the Selenium server and reset the router. If this can help anyone, here is the (simple) Python script to reset a ZyXEL 3G router through Selenium, assuming a Selenium server has been started and is listening on port 4444:

#!/usr/bin/env python 
from selenium import webdriver 
browser = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNIT) 
# Login 
pass_field = browser.find_element_by_name("textfield") 
# Click restart 
button = browser.find_element_by_name('apply') 

And here is the Bash script that controls it all, and that we call from a cronjob:

TOOLS=`dirname $0` 
# Start Selenium server 
java -jar $TOOLS/selenium-server-standalone.jar > /dev/null 2>&1 & 
sleep 10 
# Reset router 
# Kill Selenium 

If you find this to be of use I’d be happy to hear from you in the comments below.

Posted on April 26, 2012 at 9:00 am by David Lindelöf · Permalink · 4 Comments
In: Uncategorized

Floating-point woes, part 1

You may have several decades of programming experience, certain classes of problems seem to repeatedly cause endless confusion. Floating-point computation is one such class.

I’ve been doing a fair amount of numerical analysis these past few months, implementing floating-point calculations on embedded platforms. In the process I’ve stumbled across a few programming gotchas which I’d like to document in a (hopefully short) series of posts. I think that some of them are highly non-trivial, and that no amount of prior lecturing and/or reading (such as Goldberg’s excellent _What Every Computer Scientist Should Know About Floating-Point_ paper), there are still some issues that might surprise any programmer. I begin with a relatively simple and well-known example drawn from the programming class I teach.

(All the code examples in this series are available from

Termination criteria for a square-root calculating routine

Consider this program for calculating square roots by Newton’s method:


#define EPS 0.000001

static float fabsf(float x) {
return x < 0 ? -x : x;

static int sqrt_good_enough(float x, float guess) {
return fabsf(guess*guess - x) < EPS;

static float sqrt_improve(float guess, float x) {
return (guess + x/guess)/2;

static float sqrt_iter(float x, float guess) {
if (sqrt_good_enough(x, guess))
return guess;
return sqrt_iter(x, sqrt_improve(guess, x));

float sqrt(float x) {
return sqrt_iter(x, 1.0f);

int main(int argc, char** argv) {
float x = atof(argv[1]);
printf("The square root of %.2f is %.2f\n", x, sqrt(x));
return 0;

This program works well enough with arguments smaller than about 700. Above that value, one gets segmentation faults:

$ ./sqrt1 600
The square root of 600.00 is 24.49
$ ./sqrt1 1000
Segmentation fault

Debugging the progam under `gdb` shows that a stack overflow happened:

$ gdb ./sqrt1
Reading symbols from /home/dlindelof/Dropbox/Projects/fpwoes/sqrt1...done.
(gdb) run 1000
Starting program: /home/dlindelof/Dropbox/Projects/fpwoes/sqrt1 1000

Program received signal SIGSEGV, Segmentation fault.
fabsf (x=Cannot access memory at address 0x7fffff7feff4
) at sqrt1.c:6
6 static float fabsf(float x) {
(gdb) bt
#0 fabsf (x=Cannot access memory at address 0x7fffff7feff4
) at sqrt1.c:6
#1 0x00000000004005aa in sqrt_good_enough (x=1000, guess=31.622776) at sqrt1.c:11
#2 0x0000000000400610 in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:19
#3 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#4 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#5 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#6 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#7 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#8 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#9 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22
#10 0x000000000040063a in sqrt_iter (x=1000, guess=31.622776) at sqrt1.c:22

What's happening should be quite clear here. The best estimate for the square root of 1000 in single precision is 31.622776, whose square is 999.999939, differing from 1000 by about 6.1e-5, i.e. way more than the specified tolerance of 1e-6. But it is the best approximation that can be represented in single precision. In hex, it is `0x41fcfb72`. One least-significant bit (LSB) less, or `0x41fcfb71`, represents 31.6227741 whose square is 999.999817, off by 18.3e-5. One LSB more is `0x41fcfb73` or 31.6227779, whose square is 1000.00006, off by 6.1e-5, i.e. the same difference as for 31.622776. 31.622776 is therefore the best approximation to the square root of 1000 with single-point precision.

To have the program terminate instead of entering an infinite loop we need to rethink the termination criteria. Obviously we cannot use an absolute difference between the square of our guess and the argument, for as we have just seen, for large values it might not be possible to get an answer whose square is close enough to the argument.

We could imagine using a _relative_ difference instead:

static int sqrt_good_enough(float x, float guess) {
return fabsf(guess*guess - x) / x < EPS;

This gives us a second program `sqrt2.c`, which works much better:

$ ./sqrt2 1000
The square root of 1000.00 is 31.62
$ ./sqrt2 5
The square root of 5.00 is 2.24
$ ./sqrt2 2
The square root of 2.00 is 1.41
$ ./sqrt2 1
The square root of 1.00 is 1.00
$ ./sqrt2 100000
The square root of 100000.00 is 316.23
$ ./sqrt2 10000000
The square root of 10000000.00 is 3162.28
$ ./sqrt2 1000000000
The square root of 1000000000.00 is 31622.78
$ ./sqrt2 0.5
The square root of 0.50 is 0.71
$ ./sqrt2 0.1
The square root of 0.10 is 0.32
$ ./sqrt2 0.01
The square root of 0.01 is 0.10
$ ./sqrt2 0.05
The square root of 0.05 is 0.22

Interestingly, Kernighan and Plauger (in their clasic _The Elements of Programming Style_) deal with a very similar problem in the first chapter, but introduce a slightly different termination criteria. Translated into C from the original Fortran, this would give:

static int sqrt_good_enough(float x, float guess) {
return fabsf(x/guess - guess) < EPS * guess;

I asked the good folks on why one termination criteria might be better than another. I've accepted the answer that explained that the termination criteria should match the update definition. In other words, you want the termination criteria to be equivalent to saying `|guess[n+1] - guess[n]| < guess[n] * EPS`. Given that `guess[n+1] = (guess[n] + x/guess[n])/2`, one obtains a termination criteria that reads `|x/guess[n] - guess[n]| < guess[n] * EPS` --- which is exactly the termination criteria preferred by K&P.

Note furthermore that this criteria correctly handles the case when `y == 0.0`. However, the program will still eventually produce nonsense on an input of `0.0`. Quoth the debugger:

#1 0x0000000000400636 in sqrt_iter (x=0, guess=0) at sqrt3.c:22
#2 0x0000000000400646 in sqrt_iter (x=0, guess=1.40129846e-45) at sqrt3.c:22
#3 0x0000000000400646 in sqrt_iter (x=0, guess=2.80259693e-45) at sqrt3.c:22
#4 0x0000000000400646 in sqrt_iter (x=0, guess=5.60519386e-45) at sqrt3.c:22
#5 0x0000000000400646 in sqrt_iter (x=0, guess=1.12103877e-44) at sqrt3.c:22
#6 0x0000000000400646 in sqrt_iter (x=0, guess=2.24207754e-44) at sqrt3.c:22
#7 0x0000000000400646 in sqrt_iter (x=0, guess=4.48415509e-44) at sqrt3.c:22
#8 0x0000000000400646 in sqrt_iter (x=0, guess=8.96831017e-44) at sqrt3.c:22
#9 0x0000000000400646 in sqrt_iter (x=0, guess=1.79366203e-43) at sqrt3.c:22
#10 0x0000000000400646 in sqrt_iter (x=0, guess=3.58732407e-43) at sqrt3.c:22
#11 0x0000000000400646 in sqrt_iter (x=0, guess=7.17464814e-43) at sqrt3.c:22
#12 0x0000000000400646 in sqrt_iter (x=0, guess=1.43492963e-42) at sqrt3.c:22
#13 0x0000000000400646 in sqrt_iter (x=0, guess=2.86985925e-42) at sqrt3.c:22
#14 0x0000000000400646 in sqrt_iter (x=0, guess=5.73971851e-42) at sqrt3.c:22
#15 0x0000000000400646 in sqrt_iter (x=0, guess=1.1479437e-41) at sqrt3.c:22
#16 0x0000000000400646 in sqrt_iter (x=0, guess=2.2958874e-41) at sqrt3.c:22
#17 0x0000000000400646 in sqrt_iter (x=0, guess=4.59177481e-41) at sqrt3.c:22

The termination criteria will eventually involve a `0.0/0.0` operation. There is no way out of this other than to explicitly handle that special case. The final program thus reads:


#define EPS 0.000001

static float fabsf(float x) {
return x < 0 ? -x : x;

static int sqrt_good_enough(float x, float guess) {
return fabsf(x/guess – guess) < EPS * guess;

static float sqrt_improve(float guess, float x) {
return (guess + x/guess)/2;

static float sqrt_iter(float x, float guess) {
if (sqrt_good_enough(x, guess))
return guess;
return sqrt_iter(x, sqrt_improve(guess, x));

float sqrt(float x) {
if (x == 0.0) return 0.0;
else return sqrt_iter(x, 1.0f);

int main(int argc, char** argv) {
float x = atof(argv[1]);
printf(“The square root of %.2f is %.2f\n”, x, sqrt(x));
return 0;

What’s the most obscure bug involving floating-point operations you’ve ever been involved in? I’d love to hear from it in the comments below.

Posted on March 12, 2012 at 10:01 am by David Lindelöf · Permalink · Leave a comment
In: Programming