Functions as first class values and numerical method for simple integral calculation
A higher-order function is a function which takes a function as argument or returns a function.
Examples:
object HOFuncs extends App {
def sum(f: Int => Int, a: Int, b: Int):Int = {
if (a > b) 0
else f(a)+sum(f,a+1,b)
}
def sq(x: Int) : Int = x*x
def cube(x: Int) : Int = x*x*x
def usrFun(x: Int) :Int = x + x*x
println("sum(sq,1,3) = "+sum(sq,1,3)) // 1*1 + 2*2 + 3*3 = 1+4+9 = 14
println("sum(cube,1,3) = "+sum(cube,1,3)) // 1+8+27 = 36
println("sum(usrFun,1,3) = "+sum(usrFun,1,3)) // (1+1*1)+(2+2*2)+(3+3*3) = 2 + 6 + 12 = 20
}
Output:
sum(sq,1,3) = 14
sum(cube,1,3) = 36
sum(usrFun,1,3) = 20
Now I am going calculate integral of function of one variable with mathematics and with scala. Also we see graphical representation.
Imagine that function is y=x*x+1, with graphic:
Mathematically integral of this function can be calculated through primitive.
Int(with limits 0,2) of x*x+1 = x^3/3+x ,(set limits) = 2^3/3+2 - 0 = 8/3+2 ~ 2.666+2 = 4.666
And also we can remember integral definition as a square under the curve. What about graphical calculation !?
This is a scala code for calculation integral with numerical method. Intergarl as a sum of squares of narrow rectangles that populate area under the curve.
object HOFuncs extends App {
def y(x : Double) : Double = {
x*x+1
}
def numint(f: Double => Double,x : Double, xu: Double, dx :Double):Double = {
if (x >= xu) 0
else dx*f(x+dx/2) + numint(f,x+dx,xu,dx)
}
//calculate of integral of function y with limits x=0, xu=2 with step = 0.01
println(numint(y,x=0,xu=2,dx=0.01))
}
output
4.666650000000006
As you can see, here we pass function y direct as a parameter into numint. Of course there are some restrictions on this functions, it has to be defined in positive area. Otherwise we will recive negative sum of squares.


Комментарии
Отправить комментарий