Option Explicit
Sub Iteration ()
Dim i As Integer, xinit As Double, x As Double, n As Integer
xinit = InputBox ("Please enter initial guess.")
x = xinit
n - 10
For i=1 To n
x = sqr(x^(1/3) + 5 + x)
Next i
MsgBox Format Number (x, 3)
End Sub
Lab #08
You may have noticed the FormatNumber function on the second to the last line. This formats the variable x
to 3 places to the right of the decimal point (thousandths place).
What is x after 10 iterations?
Make sure your cursor is on any line within the Iteration subroutine and step through your sub using F8. Also,
verify that your locals window is open (if not, select View -> Locals Window). Using an initial guess of 4, fill in
the following table with the values of x for the first 5 iterations (the first iteration has been filled in for you):
Iteration (i in
your code)
1
2
3
4
5
X
Page 2
4.65
Change n in your code to be equal to 20 iterations. What is x after 20 iterations?/n2. In the first part of this workshop, we will be solving an equation of the form x = f(x) using iterative solving.
Computers are good at doing things over and over and iterative solving uses several to many iterations. First,
save your file as a macro-enabled workbook and name it "FirstName_LastName_Lab_08.xlsm".
We would like to solve for a root of the following equation:
x =VX1/3+5x
You should all be familiar with iterative solving; the function value (right side of equation above) is used as the
x-value for the next iteration, etc. If you are unfamiliar with iterative solving, please refresh your memory by
viewing the following screencast: https://vimeo.com/87810968
A general flowchart for iterative solving is shown below:
output x
end
N
begin
input X₁
i>n
?
X = Xo
n = 10
i=1
i=i+1
x = f(x)
In the VBE, create code for this flowchart and name your sub Iteration. You should Dim the variables xinit
(initial guess), x, i, and n. Use a value of 10 for the number of iterations (n, this can be changed later if you'd
like). Use the function above. IMPORTANT: The next page has the solution, it is way better if you try to do
this on your own before peaking at the solution!!! Ask your TA if you need help, give it your best shot before
looking at the next page!
Here is one way to write this code in the VBE:
Fig: 1
Fig: 2