Calculate the area under the curve based on calculating the area of single polygon

Hi, sorry I’m new to julia and I’m stuck trying to make based on the function that calculates the area of a polygon to calculate the area under the curve of a strictly non-negative function on a given interval [π‘Ž, 𝑏]. For this, obtain 𝑛 + 1 equidistant points in that interval ([π‘Ž, π‘Ž + (𝑏 βˆ’ π‘Ž) / 𝑛,…, 𝑏]) and with them obtain the coordinates of the vertices of the polygon that approximates the area under the curve, [π‘Ž, 0], [π‘Ž, 𝑓 (π‘Ž)], [π‘Ž + (𝑏 βˆ’ π‘Ž) / 𝑛, 𝑓 (π‘Ž + (𝑏 βˆ’ π‘Ž) / 𝑛)],…, [𝑏, 𝑓 (𝑏)] , [𝑏, 0] and finally calculates its area.
In this way:

Something like in the image, The red points are the subdivision of the inverval and the vertices of the polygon, the polygon is formed by the green lines and the function by the black curve.
I try with this, but i donΒ΄t know where is the error

area(f(x), a, b, n)
xs = a:(b-a)/n:b
deltas = diff(xs)
cs = xs[1:end-1]
sum(f(cs[i]) * deltas[i] for i in 1:length(deltas))

Here are some pointers
https://docs.julialang.org/en/v1/base/math/#Base.range
https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting
https://docs.julialang.org/en/v1/base/collections/#Base.sum

1 Like

Is this a homework problem?

(If not, what you are doing is the trapezoidal rule, and there is plenty of Julia code for this and more sophisticated methods of numerical integration.)

1 Like

Maybe I didn’t have to fiddle with the problem so much, it’s more about how to make my function use f (x), I mean this:

a, b = 0, 1
f(x) = x^2
n = 50_000
xs = a:(b-a)/n:b
deltas = diff(xs)
cs = xs[1:end-1]
sum(f(cs[i]) * deltas[i] for i in 1:length(deltas))

This is how my code works, but when I try to do it as a function, I don’t know how to evaluate it, because if I do it like this:

function Area(f, a, b, n)
xs = a:(b-a)/n:b
deltas = diff(xs)
cs = xs[1:end-1]
sum(f(cs[i]) * deltas[i] for i in 1:length(deltas))
end

Area( x^2, 0, 1, 50_000)

It gives me an error

Anonymous function input required:
Area(x -> x^2, 0, 1, 50_000)

2 Likes

Well, since f has already been defined, one can just call

area(f, 0, 1, 50_000) # function names should be lowercase, btw 
1 Like

In the second example, it was not.

1 Like