Latest posts

The Mandelbrot Set in JavaScript

On: 12.26.2009

JavaScript turns out to be a great language for toying with graphics and visualization. This morning, I spent a few hours learning about the Mandelbrot set and trying to code up a working implementation. The link below is one of the fruits of my labor:

Mandelbrot Set Generator

Mathematically, the Mandelbrot set is the set of points in the complex plane generated by iterating through the formula z = z^2 + c. For different initial values of c, the iteration can either produce a bounded sequence, or tend to infinity. Plotting the graph is a matter of placing a black dot for the values that generate a bounded sequence.



The next part of the problem is figuring out how to test for unbounded sequences. A good approximation can be reached by running through n iterations and quitting if the magnitude of z exceeds 2. The magnitude of a complex number with real part a and imaginary part b is sqrt(a^2 + b^2). For simple graphs, a reasonable value for n is 100.



Here's what a simple Mandelbrot set grapher in JavaScript looks like:

for (var x = 1; x < this.width; x++) {
for (var y = 1; y < this.height; y++) {
var count = 0;
var size = 0;
var cx = xcorner + ((x * zoom) / this.width);
var cy = ycorner + ((y * zoom) / this.height);

var zx = 0;
var zy = 0;

while (count < 100 && size <= 4) {
count += 1;
temp = (zx * zx) - (zy * zy);
zy = (2 * zx * zy) + cy
zx = temp + cx;
size = (zx * zx) + (zy * zy);
}

this.Plot(x, y, count); // count serves as a good color hint.
}
}


By setting the xcorner, ycorner, and zoom variables, the above code allows you to pan across and zoom into various points in the set. To accommodate for pretty visualizations, you can use count to determine the color of the pixel.

A barebones implementation is available here: mandelbrot.js. Although it is not a very efficient implementation, it is very simple, and if you squint hard enough, you can see how the code relates to the visualization.



The Mandelbrot Set Generator is a harness I built with mandelbrot.js. Play with the parameters and let me know if you find anything interesting. It also turns out to be a good browser speed test.

To learn more about the Mandelbrot Set, see the Wikipedia article on the Mandelbrot Set.

Google Chrome Poster from Source Code

On: 12.24.2009

This holiday weekend, I decided to compose the Google Chrome logo using the browser's own source code. I used a combination of Ruby, ImageMagick, and a heavily hacked PDF library to generate this poster.

This is the icon that I used:



Here's what it looks like zoomed in:



And zoomed in some more:



Download the PDF in all it's vectorized glory. (Approx 1.5MB. Please don't link directly to the poster.)

Take it to your favourite print shop. Since it is based on vector graphics, it can be scaled up trivially without losing quality.

Happy Holidays!

P.S. If you ask me nicely, I might send you a 24-page letter-sized split of the poster so you can print it at home. (At nearly 50MB, it's too big for me to host here.)

Vex Crypto

On: 10.26.2009

So, I was looking a place to store some of my private data, such that I could access it conveniently when I needed to. By "conveniently", I mean over a web browser at a friend's place, or in an Internet cafe.

It turns out that outside of setting up an encrypted filesystem on a remote server (or doing something similarly convoluted), there really aren't any other options.

The type of information that I need to store is usually of the personal kind, e.g., passport numbers, emergency contacts, financial or health information, etc. Basically, I'd like to have easy access to any information that comes in handy during an emergency but can't be easily carried around.

I also really wanted to do something cool with Google App Engine and jQuery.

So, I wrote this: Vex Crypto (you need a Google account to log in.)

Vex Crypto allows you to store snippets of encrypted text in the Google "cloud". It performs all the encryption and decryption in JavaScript (inside the browser), so that no plain-text information is stored on disk or transferred over the wire.

This essentially means that even people who have access to the stored data will not be able to decode it without the "decryption password".

Try it out and let me know what you think.

Everybody Loves Colors

On: 9.25.2009

Colors on terminal scripts are fun. They're also easy.
class Colors:
ESC = "\033["
PURPLE = ESC + "95m"
GREEN = ESC + "92m"
YELLOW = ESC + "93m"
RESET = ESC + "0m"

print Colors.YELLOW + "Warning: Colors enabled."
print Colors.RESET

Abbreviations in Vim

On: 4.11.2009

There are a few bits of text that are common to almost every file I edit with Vim. One of them is, of course, my name. The others are my e-mail address, and the date.

Vim allows you to define simple text abbreviations to make entering such strings super-easy. Here's a snip of my .vimrc.


" Some handy abbreviations.
"
" Insert date.
iab xdate =strftime("%Y/%m/%d %H:%M:%S")

" What's my name?
iab xname Mohit Muthanna Cheppudira

" My personal sig.
iab xsigp Mohit Muthanna Cheppudira

" My work sig.
iab xsigw Mohit Muthanna Cheppudira


With the above in my Vim configuration, the text xdate gets auto-replaced to today's date.

Slick.

Simple Code Folding in Vim

On: 4.05.2009

I've been on a Vim customization frenzy the last few days, and I just discovered an uber-cool feature: code folding. Folding is the process of rolling up a block of lines in the buffer, to a single line.

Here's what folded code looks like:



So, to unfold a block, simply move the cursor to the block and hit "zO". (All the fold commands begin with "z"). Here's what an unfolded block looks like:


There are many ways to fold code, but the simplest way to enable it is by setting the foldmethod option to indent. This folds code based on its indentation.

If you're looking for syntax-aware folding, you can set fold-method to syntax. This generally takes a little more tweaking to get the right fold behaviour.

Add the following to your .vimrc, to get simple straightforward indentation-based code folding:

" Enable folding by indentation
" Use: zc, zo, zC, zO, zR, zM
" Ctrl-K .3 for ⋯
set foldmethod=indent
highlight Folded ctermfg=red
highlight FoldColumn ctermfg=white
set fillchars=fold:⋯


For more information about code folding, and to get a list of all the commands, see http://www.vim.org/htmldoc/usr_28.html.

Generating Circular Primes

On: 3.29.2009

I've been having way too much fun with Project Euler (and Haskell) lately. Below is a listing of my solution to problem 35: "How many circular primes are there below a million?"

It solves in about 2 seconds on my laptop (using -O2). This isn't great, but not bad given that the only optimizations in the code are: a memoized prime number generator, and the use of Data.Set for quick primality tests.

-- Project Euler: Problem 35
--
-- The number, 197, is called a circular prime because all rotations of the
-- digits: 197, 971, and 719, are themselves prime.
--
-- There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37,
-- 71, 73, 79, and 97.
--
-- How many circular primes are there below one million?

import Data.Set (Set)
import qualified Data.Set as Set
import System (getArgs)

-- How many circular primes do you want?
limit = 1000000

-- Memoized prime number generator.
primes :: [Integer]
primes = 2 : 3 : 5 : filter (not . hasFactor) [7..]
where hasFactor n = any (divides n) $ takeWhile (<= lowestFactor n) primes
divides n m = n `mod` m == 0
lowestFactor = ceiling . sqrt . fromIntegral

-- Given an integer, return the number of digits in it.
digits :: Integer -> Int
digits n = ceiling $ logBase 10 $ fromIntegral (n + 1)

-- Rotate number right:
-- rotate 456 = 645
-- rotate 3498 = 8349
--
-- Note that this does not work for numbers that have zeroes in them. But
-- that's okay because any number with a zero in it is not a circular prime.
-- Also, right rotation catches the zero before it disappears into the
-- significant digit.
rotate :: Integer -> Integer
rotate n = strip_last_digit + (last_digit * tens_place)
where last_digit = n `mod` 10
strip_last_digit = (n - last_digit) `div` 10
tens_place = (10 ^ (digits n - 1))

-- Set of million primes. This enables fast lookup in isCircularPrime.
primeSet :: Set Integer
primeSet = Set.fromList $ takeWhile (< limit) primes

-- Returns True if number is prime.
isPrime :: Integer -> Bool
isPrime n = Set.member n primeSet

-- Returns True if the number is a circular prime.
isCircularPrime :: Integer -> Bool
isCircularPrime n = all isPrime $ take (digits n) $ iterate rotate n

-- Go.
main :: IO ()
main = print $ length $ filter isCircularPrime $ takeWhile (< limit) primes


So... how can I optimize this some more?