曲线下的区域以编程方式编写

时间:2016-01-26 12:35:33

标签: scala integral

我试图解决以下示例1曲线下的区域:http://tutorial.math.lamar.edu/Classes/CalcI/AreaProblem.aspx

f(x)= x ^ 3 - 5x ^ 2 + 6x + 5和x轴n = 5

答案是:25.12 但我得到的略少:23.78880035448074

我做错了什么?

这是我的代码:

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))

1 个答案:

答案 0 :(得分:0)

我猜测问题是问题是build_points(deltaX, 5, List(0.0f))返回一个包含6个元素而不是5个元素的列表。问题是你在一开始就传递一个包含一个元素的列表,其中我是#&# 39;猜测你想要一个空列表,比如

build_points(deltaX, sub, Nil)