Search code examples
scalamathareacurve

Finding area under the curve(Integration) in Scala from Array of values


Hi does anyone know of a standard library that can do what is specified in the title. Ideally the usage should be something like this: https://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html

I researched quite a lot and couldn't finding anything similar. Everything used apache PolynomialFunction class which takes as inputs the polynomial parameters and not the y-coordinates


Solution

  • Using Breeze you can write any type of function that type checks and pass it to trapezoid, you can just include the mapping in the function:

    val f = (x: Double) => {
      val xToY = Map(1.0 -> 1.0 , 2.0 -> 2.0, 3.0 -> 3.0)
      xToY(x)
    }
    
    scala> import breeze.integrate._
    scala> trapezoid(f, 1, 3, 3)
    res0: Double = 4.0
    

    Although it has restricted use, as it needs the mapping not to have gaps between the range it defined.