Friday, October 17, 2008

square root function update and code coloring

Couple things today - first, I did some benchmarking on the F# implementation of my square root approximation function. Truth is, performance sucks, as I figured it would - don't use that code in production! The built-in sqrt function ends up calling the 'fsqrt' assembly opcode, and so is orders of magnitude faster than my code.

Second, thanks to Guy Burstein for the new code syntax highlighting add-in I'm using for the blog. I was using a javascript syntax colorer, but it wasn't working correctly in RSS readers, and it was clunky to use. This new add-in I'm using allows me to copy my source as HTML, preserving the colors as seen in Visual Studio and allowing me to stick with my darker colorings - I'd have had to mess with CSS to get the old javascript colorer to match my settings, and I just didn't have the patience. Also this works properly with C#, F#, XML, HTML - anything VS displays and colorizes. You see it exactly as I see it. =)

Here's a little code sample to demonstrate. This is a little F# function showing off units of measure to calculate the speed at which a body will hit the Earth from a given height in meters, assuming the Earth has no atmosphere... Not terribly useful perhaps but here it is:

    1 #light


    3 open System


    5 let out p = Console.WriteLine(p:string)

    6 let inp = Console.ReadLine


    8 let prompt p = out p; inp()


   10 [<Measure>] type meter

   11 [<Measure>] type feet

   12 [<Measure>] type mile

   13 [<Measure>] type second

   14 [<Measure>] type hour


   16 let gAcc = 9.2<meter/second^2>

   17 let feetPerMeter = 3.28084<feet/meter>

   18 let secondPerHour = 3600.0<second/hour>

   19 let feetPerMile = 5280.0<feet/mile>


   21 let _ =

   22     let i = prompt "Enter a value"

   23     let v = ((float i) * 1.0<feet> / feetPerMeter)

   24     let spd = sqrt (2.0 * gAcc * v)

   25     let spdMpH = ((spd * feetPerMeter) * secondPerHour) / feetPerMile

   26     out ("from " ^ (string (Math.Round(float v, 4))) ^ " meters: ")

   27     out (string (Math.Round(float spd, 4)) ^ " meters/second")

   28     out (string (Math.Round(float spdMpH, 4)) ^ " miles/hour")

   29     ignore(prompt "Press enter to end")

So, enjoy!

No comments: