Search code examples
haskellcalculus

Computing left handed Riemann Sums in Haskell


I have created this function that is supposed to compute left handed Riemann sums but I am getting an answer of infinity every time I call the function. I am confused on why I would be returned infinity even though I am taking the sum of a finite list and multiplying it by deltaX.

theFunc :: Float -> Float  
theFunc x = 1 / x^2 

--aBound, bBound, function, numIntervals  
leftSum :: Float -> Float ->  (Float -> Float) -> Float -> Float  
leftSum a b f n =   
    let dx = (b-a) / n  
    in dx * (sum [f x | x <- [a,a+dx..b-dx]])

Solution

  • This error will only happen when the left interval of the Reimann sum begins at 0 because of the line:

    in dx * (sum [f x | x <- [a,a+dx..b-dx]])
    

    f x given your theFunc function becomes theFunc 0 and 1/0^2 is infinity

    Since mathematically speaking there is an asymptote at 0, this behavior is correct. If you instead want to pretend that a value at 0 does not contribute to the integral, then we can add a guard for zero like so:

    theFunc :: Float -> Float
    theFunc x
      | x == 0.0 = 0.0
      | otherwise = 1.0 / x^2 
    

    Called like:

    leftSum 0 2 theFunc 1000