nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: Experiments

I’m constantly thinking of little projects to be working on to expand my knowledge and skill-set, posts relating are filed here.

The Sieve of Eratosthenes

I recently read Prime Obsession by John Derbyshire; a book all about prime numbers and one of the worlds greatest Mathematicians: Bernhard Riemann. The books main focus is on the Riemann Hypothesis which states that:

The real part of any non-trivial zero of the Riemann zeta function is 1/2.

I’d love to say that after reading the book I understand the Maths behind it but alas I do not. That’s not surprising though as it’s a problem that has yet to be solved, 159 years after Riemann paper on “On the Number of Primes Less Than a Given Magnitude”. It doesn’t look like it’s going to be solved any time soon either! If you’re interested it’s one of the Clay Mathematics Institutes Millennium Prize Problems in which you can earn yourself US$1,000,000.

While reading Prime Obsession it mentioned an interesting method for finding prime numbers called “Sieve of Eratosthenes” (pronounced air-a-TAWS-the-nEEss). Eratosthenes was a librarian at the great library of Alexandria around 230 B.C.E. It’s quite obvious how the method works once you know it, and easy to see why it’s called a sieve. The method goes like this:

  1. Write a list of numbers in which you wish to identify the primes, say 2 – 100 (exclude 1 as it isn’t required)
  2. Take the first number 2. Leaving 2 intact, remove every second number.
  3. Move onto the next number 3. Leave 3 intact and remove every third number
  4. Take the next number 5. Leave 5 intact and take away every fifth number
  5. Repeat until you get to the end of your list

The end result is the set of prime numbers up to your given number. Essentially all you are doing is removing any number that is divisible by the 1st, 2nd… Nth number. Clever stuff!

As a little side project I decided to implement this method using JavaScript, displaying the result in the browser. You can view the demo here. For fun I created two implementations, one relying heavily on the DOM, the other only using arrays. As you’d expect the DOM method is slow; looping through large tables multiple times doesn’t make for a quick execution time. The second method using a single JavaScript array is much quicker. I’ve added a stats panel to the right hand side of the page so it’s possible to compare results from both methods over different input values.

I’ve added a limit to the number you can enter into the input box (5000), I don’t want anyone blaming me for crashing their browser by entering 10 million! :) Feel free to copy the demo if you want to see what happens at higher values.

Sieve of Eratosthenes using JavaScript

The sieve in action showing prime numbers up to 500.

Thanks goes to John Resig for his very handy Array Remove method.It made removing non-primes from the numbers array very simple indeed.

Prime Obsession is a superb book but a word of warning, it contains a lot of higher level Mathematics, so may not be to everyone’s taste. It certainly made my brain hurt at times; not always what you need on that 8am commute to work! View the demo.

Creating 3D trees with some #CreativeJS

Random trees created using three.js and some creative JavaScript

Trees generated at random using some CreateiveJS and Three.js.

Over a month has passed since my last blog post and much has happened. We’ve had a wedding, a funeral at sea (maybe in bad taste!) and I’ve gone full-time freelance (yay!). I’ve had a little more time to work on a couple of personal projects so I’ve finished one that I started way back in January.

I had the pleasure of attending a Creative JavaScript course in Brighton, UK, hosted by Seb Lee-Delisle; a two-day course that covered a wealth of topics from Vanilla JavaScript to Three.js. If you’re looking for some inspiration I highly recommend looking out for one of Seb’s courses. Great fun and you get to meet some really nice people. Quick tip: You may want to brush up on a little Trigonometry before you go as it’s used numerous times. I knew that A-Level Mathematics course would come in useful one day :).

Seb produced a demo in Canvas that created ‘trees’ and it really caught my eye. The trees were in 2D so as I’ve had a bit of experience with Three.js I decided to create a 3D version! I’m quite happy with the result although I’ve had to restrict the number of branches rendered due to the lack of dedicated graphics card in my laptop; I get about 1fps when stopping at a branch length value of 10 (line 211) :(

The demo also allowed me to use the new request animation frame API which vendors have added to aid animations in browsers. The main advantage of using it is if you have the animation running in a tab that isn’t visible, the browser will know to stop the animation! Using the old setTimeout method, the animation still runs in the background and uses up precious CPU, memory and battery power (especially on a laptop). As with most new browser features the API isn’t set in stone (yet) but luckily Paul Irish has created a polyfill that falls back to setTimeout in older browsers.

View the demo here; reload for different trees. JavaScript finally seems to be coming of age!

Update: Original credit goes to Jean-No with his amazing OpenProcessing work! I’ll be bookmarking that link, some stunning work there. Thanks to Seb for pointing out who to credit :)

Visual thesaurus using arbor.js

Wow, I can’t believe we are at the end of January – one twelfth of the year gone already! I’ve been so busy this month I’ve barely had time to sit down and work on any personal projects. Thankfully I had a spare few hours over the weekend to work on a project I’ve been meaning to finish for a couple of weeks: a visual thesaurus using JavaScript.

Visual Thesaurus using JavaScript

Visual thesaurus representation of the word 'clean'.

You may (or may not) know of the Visual Thesaurus by Thinkmap; very useful but it’s a paid for service, I use it so infrequently I can’t justify paying for it (there is a free trial though). Recently a very interesting graph visualisation library popped up on delicious called arbor.js, so I decided to have a closer look and see if I could use it for the JavaScript version. For the word data I’ve used the Bighugelabs thesaurus API which I previously used to create my Post Thesaurus WordPress plug-in (shameless plug!).

Arbor.js took a little getting used to as it uses a mixture jQuery, canvas and its own methods; but there’s a fairly extensive set of documentation and a set of usage examples. Once you get your head around adding nodes and edges to the system, arbor takes care of the rest. One thing I did notice is the site examples and my VT experiment run much smoother in Firefox than they do in Chrome, which is quite surprising considering how quick the V8 engine is in Chrome. Maybe this will be improved in future versions.

So to the demo; I’ve tried to keep it very simple to use. Enter the word you wish to visualise and click search. Once the API returns a result it’s plotted by arbor. You can drill down into the result by clicking on the sub-particles (and remove them by clicking again). The individual words can be clicked and you’re given the option to search again using the selected word. I still haven’t got the perfect system setup as some results can be a little jittery; usually when an even set of words are returned. I’ll keep playing with system settings to see if I can improve this.

Any suggestions, comments or feature improvements please leave a comment below!

A three.js community on Reddit

Well 2011 is nearly upon us; which leaves me thinking… where did 2010 go! I hope I’m not the only one who thinks this year has gone quick! One big web application that died in 2010 was digg.com. I used to use it every day for the latest technology and funny videos, but then they changed it. The design became very blue and digg seemed to change from a simple community driven link aggregator to a, well, I’m not sure what it changed to in all honesty. So it was time to find an alternative.

Luckily for me (and all digg users) there’s already a well established alternative: reddit.com. It may not look as flashy as digg, but it makes up for it with ease of use and functionality. Need to set up a community for your web application, current technology, interest or well, just about anything really; then reddit is the place for you.

So that’s exactly what I’ve done for Mr. doobs three.js JavaScript library. I created a Threejs community that anyone can submit links to relating to three.js. Over the past few weeks I’ve been adding a couple of links a day, there really are a great selection of examples out there if you take the time to hunt then down.

So if you’ve created a cool new example using three.js or any other link relating to this excellent JavaScript library submit it here. Digg is dead. Long live reddit.com!

Experimenting with Webkit form speech input

It’s been a few weeks now since I attended a Web Gaming event hosted by Mozilla and I’ve not yet had chance to write about one of the coolest features that was demonstrated: Speech input in forms. Now I must admit, I had no idea this was even possible; so it was quite a surprise when I saw the demonstration. With a few extra attributes added to a standard input box you can enable speech input:

1
<input name="speech" id="speech" type="text" x-webkit-speech speech error onwebkitspeechchange="dosomething.coolhere(true);" />

It really is that simple! You may notice the “x-webkit-speech” attribute so will have guessed it currently only works in Webkit; and as far as I’m aware only in very recent versions of Google Chrome (note: “The Input Speech API will now be available by default on Chrome’s dev-channel”). The Speech API seems very new and is still a draft, so it will be a while before it’s fully adopted by other browser vendors.

Demo of the new HTML5 Speech API

A quick demonstration of the Speech API in action.

To demonstrate the speech input I’ve put together a very simple festive demo that queries the Flickr API looking for images related to a value entered. So if you have a microphone and the dev channel of Chrome, why not give it a try. Chrome records the input of the microphone before sending it off to an external server to be processed, where a value is then sent back to the browser. At first I thought it was all processed inside the browser but I guess that’s a little to much to expect! It isn’t 100% accurate and the demo accepts Googles first guess so you may get a few strange results. The server returns multiple guesses which a user can select from, but this hasn’t been added (to my demo at least).

Since the API is very new it took a little trial and error to work out how to detect if the Speech API was available in the browser; but with a little help from Paul Irish I managed to crack it:

1
2
3
4
5
function speechcapable(){
    var elem = document.createElement('input');
    var support = 'onwebkitspeechchange' in elem || 'speech' in elem;
    return support;
}

This function will return true if the API is available. It’s worth noting that since it’s very new this function is likely to break in the future as the properties always seem to be changing. It works at the moment, so get thinking about what this brilliant new API can be used for! It’s a big plus for accessibility if used correctly and I can also see some cool applications in web gaming too. View the demo.

Currently on page 2 of 612345Last »