Posts Tagged ‘Math’

Haskell Mandelbrot Set

Some people sing carols every XXX-mas, I get bored and write the Mandelbrot Set program in whatever my favorite language happens to be that year. I thought the brevity of the output this year (Haskell) was kinda neat.

import Graphics.UI.GLUT
import Control.Monad
import Data.Int
import Data.Complex

iterations = 400

x // y = fromIntegral x / fromIntegral y

-- Divides [a] into [[a], [a], ...] with each sublist of length n,
-- except the last sublist which has length <= n.
chunkify n [] = []
chunkify n xs = let (xs', rest) = splitAt n xs
                in xs' : chunkify n rest

-- Converts a coordinate in screen space to a vertex.
pix2vert (Size w h) (x, y) = Vertex2 ((3 // w * fromIntegral x) - 2.0)
                             ((2 // h * fromIntegral y) - 1.0)

-- List of all of the vertices that represent screen pixels.
vertices :: IO [Vertex2 GLfloat]
vertices = get windowSize >>= \(Size w h) ->
           return $ [pix2vert (Size w h) (x, y) | x <- [0..w-1], y <- [0..h-1]]

-- Gets the color for a number of iterations.
color3 r g b = Color3 r g b
getcolor :: Int -> Color3 Float
getcolor iter | iter == iterations = color3 0 0 0
              | otherwise          = color3 (amt*0.5) amt (amt*0.5)
              where amt = iter // iterations

-- Returns the number of iterations <= the maximum iterations of the
-- Mandelbrot set at the given vertex.
mandel (Vertex2 r i) = length . takeWhile (\z -> magnitude z <= 2) .
                       take iterations $ iterate (\z -> z^2 + (r :+ i)) 0

-- plots one point.
drawVert v = do color . getcolor $ mandel v
                vertex v

-- draws all the vertices in slices (to update the display while drawing).
display' chunks = do mapM_ (\vs -> do renderPrimitive Points $ mapM_ drawVert vs
                                      flush) chunks
                     displayCallback $= display

-- draws the whole fractal
display = do clear [ ColorBuffer ]
             displayCallback $= (vertices >>= display' . chunkify 256)
             get currentWindow >>= postRedisplay

main = do
   getArgsAndInitialize
   initialDisplayMode $= [ SingleBuffered, RGBMode ]
   initialWindowSize $= Size 1200 1024
   initialWindowPosition $= Position 100 100
   createWindow "Mandelbrot"
   clearColor $= Color4 0 0 0 0
   matrixMode $= Projection
   loadIdentity
   ortho (-2) 1 (-1) 1 (-1) 1
   displayCallback $= display
   mainLoop

Screenshot:

Mandelbrot Set written in Haskell

Dan McKinley does not claim to be a Haskell expert and definitely doesn't claim to be an expert about Haskell graphics rendering.

I’m All Sixes and Sevens and Nines

The following is a review of A Mathematician Plays the Stock Market, by John Allen Paulos.

One of my inaugural tasks at my current job was developing a technical analysis package for market data. I have to admit I rather enjoyed this, for a few reasons only tangentially related to the specific technology at hand.

First, I like solving math problems–always have. Writing programs that do this for me are more enjoyable still. Second, there was the shameful thrill of scrawling some equations involving capital sigmas (the kind of thing those of us destined to be computer scientists are doing by eighth grade) on a whiteboard and watching the panicked expressions of the business and finance people present.

I guiltily concede that the latter motivation was the dominant one. I still keep a sheet with sigmas painted all over it within reach. Anytime I’m asked about the output of my analysis package, I produce it from deep within my desk which by the way, overwhelmingly contains only ketchup (Heinz) and straws (plastic, non-bending). I’ll scribble some new symbols on it and say something like, “so as you can see, the limit of this term as phi approaches infinity is…” and before I’ve finished the sentence the person has muttered something in bewilderment and shuffled away.

dice

I’m not necessarily doing this out of malice or contempt, it’s just that I realized a long time ago that the technical analysis of market data is largely a crock. I’ve always carried this nagging little fact with me, and at times I’ve pondered the morality of having this job at all. So I’m not really doing the user a disservice here, unless I’m somehow expected to explain to everyone in the world that you can find meaningful patterns in any set of data–words in the bible, petals on a flower, sand on the beach, or the price of Superconductor (NasdaqSC:SCON). Chances are, the pattern that you discover holds no predictive power.

So it’s really not important to the person asking what the answer is, it’s just reassuring to believe that I possess one. In the end, they will probably make about as much money as chance would dictate. Maybe a little more, maybe a little less. If they do happen upon the holy grail, that ineffable oracle of a model that really can forecast the future, it is as likely to be in spite of my explanation as it is to be caused by it. Populus vult decipi; decipiatur.

How odd it is, I found myself thinking while reading this book, that there exists a Nobel prize for Economics yet none for Mathematics. Is my support for this book just another example of confirmation bias? I’m obviously not qualified to say. I suggest you judge it for yourself.

A Plea for Change in Sports Commentary

Here is one football statistic that I never want to hear again:

Team X is 40-0 when they have someone rush for 100 yards.

The conclusion you are supposed to draw is that Team X should try to run the football. Here's one way you could rephrase the statistic:

Team X does a pretty good job of winning when they're winning.

It's post hoc reasoning, people! Come on! I'm starting to think Howard Cosell was on to something when he spent years hating on Frank Gifford because he was not a trained sports journalist. I don't have a high opinion of journalists either, but now the Giffords are the norm in the commentary business. The intelligence of the analysis suffers. I'm all for coaches-as-commentators, but I think we should all agree that players-as-commentators is not working out.

Press Innumeracy

I just finished reading this Reuters story, "Rising Sea Levels Threaten New Jersey." Nevermind the obvious question of whether we'd really be menaced by the disappearance of New Jersey. I would like to focus on details tangential to the main story, as is my custom.

Notice the next-to-last paragraph,

Worldwide, sea levels are expected to rise between 0.09 and 0.88 meter (0.29 and 2.88 feet) between 1990 and 2100, the report said, citing figures from the Intergovernmental Panel on Climate Change.

Do you see anything amiss? Many scientists and engineers in the audience have already leapt out of their seats. I will explain the problem anyway, for those of you trained in the humanities.

The issue is one of precision. Or rather, too much of it.

What most likely occurred is that the Journalism major who wrote this lifted the metric figures from the published paper. Writing for a U.S. audience, he obviously needed English equivalents.

If you plug 0.09 and 0.88 meters through a conversion calculator, you get 0.29527559055118110236220472440945 feet and 2.8871391076115485564304461942257 feet, respectively. The author made the rookie mistake of cutting these off at the same number of decimal places.

This author, like most reporters, does not understand significant figures. The trouble is that the metric numbers quoted give one and two significant digits, respectively. His converted numbers erroneously give two and three significant digits.

I have gone to the trouble of rewriting his paragraph for him.

Worldwide, sea levels are expected to rise between 0.09 and 0.88 meter (0.3 and 2.9 feet) between 1990 and 2100, the report said, citing figures from the Intergovernmental Panel on Climate Change.

You may think that this is a silly thing for me to be complaining about. Not so. Significant digits are one of the first lessons in every science class, from elementary school through the first few semesters of college. Anyone doing science reporting should at least be familiar with significant digits.

Given this, it is not difficult to understand why there is so much confused and idiotic coverage of the Dover Design trial (I am on board with refusing to call it "Intelligent") and why it is reported at least once a year that the speed of light has been exceeded (Everyone say it together with me: "Phase velocity vs Group velocity").

A Macroeconomic Theory of Texas Holdem

I am having a banner day as an intellectual, it being no coincidence that my television is currently broken. I could take this excellent opportunity for creative output to bemoan yet another unfathomably stupid government-funded “power of prayer” study, but I opted for a more lighthearted subject.

To be completely candid, I started doing just that, but I depressed myself too much to finish it.

Therefore, I will regale you, the reader, with a dissertation on another utterly important subject. Namely, gambling.

Trading emails with a friend the other day, I described the poker craze that is gripping the nation as “the pet rock of this era.” I was immediately taken to task and told to defend this statement.

The argument I was given went about like this.

If one is an expert at poker, one can expect to win consistently. That’s much more than you can hope to get from other games of chance like blackjack or craps, so why would anyone lose interest in poker, given the unwavering popularity of those games?

Forget that it’s on television; once you’re into poker, I think you are hooked for life.

First let me say that I am not backing my response with any hard data. This is purely an academic exercise.

Poker suffers from an important handicap: it is necessarily worse than a zero-sum game. The winners are few, and in large tournaments or online walk away with somewhat less than what the losers have given up.

The idea that an adroit player can consistently come out the better appears to be all-too-true. But rather than being an asset, this is the very reason why poker will not continue in popularity. For every player that wins consistently, there are players who lose just as consistently.

These players plainly will not be interested indefinitely. They have sprouted like reeds from the Nile-esque deluge of ESPN coverage for the time being; in fact, this is making it significantly easier to be one of the lucky few who leave with chips.

When the plebeian interest wanes, the game’s talent bar will steadily rise. Ultimately, nearly all of those who currently style themselves as among the upper echelons will look around only to see that they are in free fall.

This kind of analysis is not difficult to derive; why is it that so few take the trouble to do it?