0

im trying to solve for the area under the curve of the example 1 of: http://tutorial.math.lamar.edu/Classes/CalcI/AreaProblem.aspx

f(x) = x^3 - 5x^2 + 6x + 5 and the x-axis n = 5

the answers says it is: 25.12 but i'm getting a slightly less: 23.78880035448074

what im i doing wrong??

here's my code:

import scala.math.BigDecimal.RoundingMode

def summation(low: Int, up: Int, coe: List[Int], ex: List[Int]) = {

def eva(coe: List[Int], ex: List[Int], x: Double) = {
  (for (i <- 0 until coe.size) yield coe(i) * math.pow(x,ex(i))).sum

}


@annotation.tailrec
def build_points(del: Float, p: Int, xs : List[BigDecimal]): List[BigDecimal] = {
  if(p <= 0 ) xs map { x => x.setScale(3, RoundingMode.HALF_EVEN)}
  else build_points(del, p - 1, ((del * p):BigDecimal ):: xs)
}

  val sub = 5
  val diff = (up - low).toFloat
  val deltaX = diff / sub
  val points = build_points(deltaX, sub, List(0.0f)); println(points)
  val middle_points =
    (for (i <- 0 until points.size - 1) yield (points(i) + points(i + 1)) / 2)


  (for (elem <- middle_points) yield deltaX * eva(coe,ex,elem.toDouble)).sum

}
val coe = List(1,-5,6,5)
val exp = List(3,2,1,0)
print(summation(0,4,coe,exp))
matos416
  • 85
  • 4
  • Side note: see also http://stackoverflow.com/questions/588004/is-floating-point-math-broken – jub0bs Jan 26 '16 at 13:39

1 Answers1

0

I'm guessing the problem is that the problem is build_points(deltaX, 5, List(0.0f)) returns a list with 6 elements instead of 5. The problem is that you are passing a list with one element in the beginning, where I'm guessing you wanted an empty list, like

build_points(deltaX, sub, Nil)
Martin Kolinek
  • 2,010
  • 14
  • 16