Keyword density is hard to figure out.... The different engines likes different keyword density. Some engines counts keywords in comment tags, alt tags, headers, reference links ect. Others don`t (or counts only some of the tags). Some count plurals and non plurals, upperchase and lowerchase keywords the same. Others don`t. Then the question is are you goung to calculate only visible text or all the coding/hidden tags?
When analysing top ranked pages, keep in mind they might have changed since submittion. Also there may be huge differences in the keyword density between the top 3 pages in a spesific keywordsearch.
Then it is a lot of other factors, where the keywords are located at the page, number of links to the site in question, how long it has been indexed ect.
I have just began to looking into this calculating of keyword densety. Think I have a huge job in front of me before I get the "secret formula" :-)