# How to Plot this Riemann Sum Correctly?

Hi all,

I have a function : x^{3} - 5x^{2} + 2x + 8 and I have this code:

``````using Plots, LaTeXStrings, ValidatedNumerics
gr()

f(x) = x^3 - 5x^2 + 2x + 8

#plot(f, 0, 2, aspect_ratio=:equal, fill=(0, :green), alpha=0.2, label="")

function make_intervals(N=6)
xs = range(0, stop=5, length=N+1)
return [xs[i]..xs[i+1] for i in 1:length(xs)-1]
end

# Plot Riemann Sums
intervals = make_intervals(6)

p = plot(aspect_ratio=:equal)
for X in intervals
Y = f(X)
plot!(IntervalBox(X, Interval(0, Y.lo)), c=:blue, label="", alpha=0.1)
plot!(IntervalBox(X, Interval(Y.lo, Y.hi)), c=:red, label="", alpha=0.1)
end

plot!(f, 0, 5, xlims=(0, 5), ylims=(-1,18), label=L"x^{3} - 5x^{2} + 2x + 8")
``````

but the plot is far from the image I want to achieve. Which lines should I modify? If I modify your code as such:

``````
f(x) = x^3 - 5x^2 + 2x + 8

function make_intervals(N=6)
xs = range(0, stop=5, length=N+1)
return [[xs[i],xs[i+1]] for i in 1:length(xs)-1]
end

# Plot Riemann Sums
intervals = make_intervals(6)
p = plot()
for X in intervals
Y = f.(X)
box = IntervalBox([X,0],[X,(Y+Y)/2],)
plot!(box,c=:blue,legend=nothing,alpha=.3)
end
plot!(f, 0, 5,c=:red)

``````

I get the following output: You will see that I take the mean of the function values for each interval, you can change that in the way that you find suitable.

3 Likes

It is great, what if I want to create the partition points on the interval [0,5] for x at 0 < 1.1 < 2 < 3.2 < 4 < 5 ? can I change the red line or adjust it to hit the right points?

``````using Plots, LaTeXStrings, ValidatedNumerics, Plots.PlotMeasures
gr()

f(x) = x^3 - 5x^2 + 2x + 8

function make_intervals(N=5)
xs = range(0, stop=5, length=N+1)
return [[xs[i],xs[i+1]] for i in 1:length(xs)-1]
end

# Plot Riemann Sums
intervals = make_intervals(5)
p = plot()
for X in intervals
Y = f.(X)
box = IntervalBox([X,0],[X,(Y+Y)/1.5],)
plot!(box,c=:blue,legend=nothing,alpha=.3)
end
plot!(f, 0, 5, xlims=(0, 5), ylims=(-6,18),
label="",
c=:red)

plot!([0.5,0.5],[0,f(0.5)], label="", linecolor=:green, linestyle=:dot)
plot!([1.5,1.5],[0,f(1.5)], label="", linecolor=:green, linestyle=:dot)
plot!([2.5,2.5],[0,f(2.5)], label="", linecolor=:green, linestyle=:dot)
plot!([3.6,3.6],[0,f(3.6)], label="", linecolor=:green, linestyle=:dot)
``````