Having a dual core processor is a great thing for the operating system; but how can you make use of this cool technology as a (mere mortal) programmer? Potentially a complex issue but if you use Scala you'll be pleasantly surprised. It is the concept of Actors and message passing that saves the day. Let me explain using an example from mathematics.
A problem that can theoretically benefit from multiple cores is the one that calculates the integral of a function. Using the simple quadrature method this problem is reduced to calculating the area of all the rectangles that follow the curve, and adding these up to produce an estimate of the integral. More rectangles provide a more accurate evaluation. The image (from wikipedia) should help you get the picture.
Here is that algorithm coded in Scala:
type R = Double
def integrate(f : R=>R , a : R, b : R, intervalCount : Int ) = {
val intervals = (1 to intervalCount)
val width = (b-a) / intervalCount
val halfW = width/2.0
(0.0 /: intervals) {
(s,i) => s + width * f(a + i * width - halfW)
}}
Note that I created a type alias for Double called R. An interesting piece of code here is the last line of the function. The /: operator is the foldleft operator. This foldleft starts with a value of 0.0 and calculates the sum of width * f(a + i * width - halfW) for each i in intervals.
To calculate the integral of the Sine function from 0 to 90 degrees using 100 rectangles , the Scala function call looks like this:
integrate(Math.sin,0,Math.toRadians(90),100)
Note that I pass the Java sine function as an argument. The answer is 1.0000102809119051 Increasing the number of rectangles to 10000 gives a better estimate: 1.0000000010280816.
Here's how I can use my dual core CPU to calculate the integral faster: divide the calculation into two smaller calculations and get each core to calculate the result of a smaller part; then add up the two results and voila I am done. The two parts are defined by using the midpoint between a and b and allowing one core work on the rectangles less than this midpoint while the other core chows the rectangles that are greater than the midpoint . Thus, if I want 10 000 rectangles, each core would do 5000 calculations.
Here's the divide and conquer algorithm in Scala:
0 comments:
Post a Comment