Write the following integration routines: 1) a Left Handed Riemann Sum routine 2
ID: 1747348 • Letter: W
Question
Write the following integration routines:
1) a Left Handed Riemann Sum routine
2) a Right Handed Riemann Sum routine
3) A trapazoidal Riemann Sum routine
4) A routine which uses Simpson's rule (see:http://en.wikipedia.org/wiki/Simpson's_rule for moreinformation.)
C++ prototypes:
double lhrs(double f[], double x[], int num)
double rhrs(double f[], double x[], int num)
double trap(double f[], double x[], int num)
double simpsons(double f[], double x[], int num)
where f[] holds values of the function to be integrated and x[]the x coordinates of the points such that f[i]=f(x[i]), and botharrays are of length num.
Explanation / Answer
Private Sub btnCompute_Click()
Dim deltaX As Double, L As Double, R As Double, M As Double, T AsDouble, S As Double, n As Long, x As Double, b As Double, a AsDouble
M = 0: T = 0: S = 0 'initializethe totals to 0, M is Midpoint, T is Trapozoid, S is Simpson
a = 1: b = 3: n = 1000000 'a and b are the limits of integration, nis the number of elements
deltaX = (b - a) / n 'deltaX is the size of each element
'Lefthand
For x = a To b Step deltaX
L = L + f(x) * deltaX
Next x
'Righthand
For x = a + deltaX To b + deltaX Step deltaX
R = R + f(x) * deltaX
Next x
'Midpoint
For x = a + 0.5 * deltaX To b - 0.5 * deltaX Step deltaX
M = M + f(x) * deltaX
Next x
'Trapozoid
T = 0.5 * deltaX * (f(a) + f(b))
For x = (a + deltaX) To (b - deltaX) Step deltaX
T = T + 0.5 * 2 * f(x) * deltaX
Next x
'Simpson
If Even(n) = True Then
S = (deltaX / 3) * (f(a) + f(b)) 'Dothe ends
S = S + 4 * f(a + deltaX) * (deltaX / 3) 'Do the1st term multiplied by 4
For x = (a + deltaX + deltaX) To (b - deltaX)Step deltaX * 2
S = S + 2 * f(x) *(deltaX / 3)
S = S + 4 * f(x +deltaX) * (deltaX / 3)
Next x
End If
Print L, R, M, T, S 'outputsthe values of Midpoint, Trapezoid, and Simpson
Text1.Text = Str$(L) + " " + Str$(R) + " "+ Str$(M) + " " + Str$(T) + " " + Str$(S)'outputs them again to a text box
End Sub
Function Even(n As Long) AsBoolean
If n / 2 = Int(n / 2) Then Even = True
End Function
Function f(x As Double) AsDouble
Dim pi As Double
pi = Atn(1) * 4
'put whatever function you're evaluatinghere
'f = Exp(-Sqr(x))
'f = Sqr(1 + (Log(x) + 1) ^ 2)
'f = Sqr(1 + (Atn(1) * 4 * Cos(Atn(1) * 4 * x /7) / 7) ^ 2)
'f = 2 * pi * Log(x) * Sqr(1 + 1 / x ^ 2)
f = Sqr(x)
End Function
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.