Excel VBA Code

ME Study
0

Newton Repshons Method

1. Command Box:

Private Sub NewtonRapshon_Click()

    ActiveSheet.Cells.Clear

    Dim MaxIter As Integer

    Dim MaxErr As Double

    Dim x0 As Double

    Dim NumIter As Integer

    Dim err As Double

    Dim xold As Double

    Dim xnew As Double

    Dim fold As Double

    Dim dfold As Double

    


    x0 = InputBox("Initial guess ")

    Cells(1, 1).Value = "Initial guess "

    Cells(1, 2).Value = x0


    MaxErr = InputBox("Enter maximum % error")

    Cells(2, 1).Value = "Maximum % error "

    Cells(2, 2).Value = MaxErr

    

    MaxIter = InputBox("Enter maximum number of iterations")

    Cells(3, 1).Value = "Maximum number of iterations "

    Cells(3, 2).Value = MaxIter

    

    Cells(5, 1).Value = "Iter No"

    Cells(5, 2).Value = "x"

    Cells(5, 3).Value = "% error"

    

    

    xold = x0

    err = MaxErr + 0.001

    NumIter = 0

    

    Do While ((NumIter < MaxIter) And (err > MaxErr))

        fold = Cos(xold) - xold ^ 3

        dfold = -Sin(xold) - 3 * (xold ^ 2)

        xnew = xold - (fold / dfold)

        err = Abs(1 - xnew / xold) * 100      

        NumIter = NumIter + 1

        Cells(NumIter + 5, 1).Value = NumIter

        Cells(NumIter + 5, 2).Value = xnew

        Cells(NumIter + 5, 3).Value = err

        xold = xnew

    Loop


End Sub


2. Function:


Public Function NewtonRapshon() As Variant()


    Dim temp() As Variant

    

    Dim MaxIter As Integer

    Dim MaxErr As Double

    Dim x0 As Double

    

    Dim NumIter As Integer

    Dim err As Double

    Dim xold As Double

    Dim xnew As Double

    Dim fold As Double

    Dim dfold As Double

    


    x0 = InputBox("Initial guess ")


    MaxErr = InputBox("Enter maximum % error")

    

    MaxIter = InputBox("Enter maximum number of iterations")

    

    ReDim temp(1 To MaxIter + 1, 1 To 3)

    

    xold = x0

    err = MaxErr + 0.001

    NumIter = 0

    

    

    temp(NumIter + 1, 1) = " Iteration "

    temp(NumIter + 1, 2) = " Error "

    temp(NumIter + 1, 3) = " Root "

    

    Do While ((NumIter < MaxIter) And (err > MaxErr))

        fold = Cos(xold) - xold ^ 3

        dfold = -Sin(xold) - 3 * (xold ^ 2)

        xnew = xold - (fold / dfold)

        err = Abs(1 - xnew / xold) * 100

        

        NumIter = NumIter + 1

        

        xold = xnew

        

        temp(NumIter + 1, 1) = NumIter

        temp(NumIter + 1, 2) = err

        temp(NumIter + 1, 3) = xnew

    Loop

    

    NewtonRapshon = temp


End Function



Private Sub CommandButton1_Click()
  Dim emptyRow As Long
  
   'Make Sheet1 active
   Sheet1.Activate
  
   'Determine emptyRow
   emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
  
    ActiveSheet.Cells.Clear
    Dim MaxIter As Integer
    Dim MaxErr As Double
    Dim x0 As Double
    
    'Transfer information
    x0 = TextBoxX0.Value
    MaxErr = TextBoxMaxErr.Value
    MaxIter = TextBoxMaxIter.Value
    
      
    Dim NumIter As Integer
    Dim err As Double
    Dim xold As Double
    Dim xnew As Double
    Dim fold As Double
    Dim dfold As Double
    
    Cells(1, 1).Value = "Initial guess "
    Cells(1, 2).Value = x0
    Cells(2, 1).Value = "Maximum % error "
    Cells(2, 2).Value = MaxErr
    
    Cells(3, 1).Value = "Maximum number of iterations "
    Cells(3, 2).Value = MaxIter
    
    Cells(5, 1).Value = "Iter No"
    Cells(5, 2).Value = "x"
    Cells(5, 3).Value = "% error"
    
    
    xold = x0
    err = MaxErr + 0.001
    NumIter = 0
    
    Do While ((NumIter < MaxIter) And (err > MaxErr))
        fold = Cos(xold) - xold ^ 3
        dfold = -Sin(xold) - 3 * (xold ^ 2)
        xnew = xold - (fold / dfold)
        err = Abs(1 - xnew / xold) * 100
        
        NumIter = NumIter + 1
        Cells(NumIter + 5, 1).Value = NumIter
        Cells(NumIter + 5, 2).Value = xnew
        Cells(NumIter + 5, 3).Value = err
        xold = xnew
    Loop
    
    LabelRoot.Caption = CStr(xnew)
    LabelError.Caption = CStr(err)
    
    Dim ws As Worksheet
    Dim rngData1, rngData2 As Range
    Dim cht1, cht2 As Chart
    Dim chtObj1, chtObj2 As ChartObject
     
    Dim startCell As Range
    Dim endCell As Range
    
    'Define the worksheet and data range for the chart
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your actual sheet name
          
     ' Define the start and end cells using row and column numbers (e.g., A1 and C5)
    Set startCell = ws.Cells(6, 2)
    Set endCell = ws.Cells(NumIter + 5, 2)
    ' Use the Range property with the two cell references
    Set rngData1 = ws.Range(startCell, endCell)
    
    Set chtObj1 = ws.ChartObjects.Add(Left:=200, Top:=200, Width:=200, Height:=200)
    
    ' Get the Chart object from the ChartObject
    Set cht1 = chtObj1.Chart
    
    cht1.ChartType = xlLine
    cht1.SetSourceData Source:=rngData1
    
    Set startCell = ws.Cells(6, 3)
    Set endCell = ws.Cells(NumIter + 5, 3)
    ' Use the Range property with the two cell references
    Set rngData2 = ws.Range(startCell, endCell)
    
    Set chtObj2 = ws.ChartObjects.Add(Left:=500, Top:=200, Width:=200, Height:=200)
    
    ' Get the Chart object from the ChartObject
    Set cht2 = chtObj2.Chart
    
    cht2.ChartType = xlLine
    cht2.SetSourceData Source:=rngData2
    
End Sub
Private Sub UserForm_Initialize()
   
   TextBoxX0.Value = ""
   TextBoxX0.SetFocus
   
   'Empty all other text box fields
   TextBoxMaxErr.Value = ""
   TextBoxMaxIter.Value = ""
End Sub



Bisection Method

1. Command Button:

Private Sub Bisection_Click()

Dim a As Double, b As Double, c As Double, d As Double
Dim fa As Double, fb As Double, fc As Double
Dim MaxIter As Integer, NumIter As Integer
Dim Tol As Double

a = InputBox("Enter the lower bound 'a':")
Cells(1, 1).Value = "Lower bound value, a"
Cells(1, 2).Value = a

b = InputBox("Enter the upper bound 'b':")
Cells(2, 1).Value = "Upper bound value, b"
Cells(2, 2).Value = b

Tol = InputBox("Enter the tolerance:")
Cells(3, 1).Value = "Tolerance"
Cells(3, 2).Value = Tol

MaxIter = InputBox("Enter maximum number of iterations")
Cells(4, 1).Value = "Maximum number of iterations"
Cells(4, 2).Value = MaxIter

Cells(6, 1).Value = "Iter"
Cells(6, 2).Value = "a"
Cells(6, 3).Value = "b"
Cells(6, 4).Value = "c"
Cells(6, 5).Value = "fa"
Cells(6, 6).Value = "fc"

NumIter = 0

fa = a ^ 3 - 6 * (a ^ 2) + 11 * a - 6
fb = b ^ 3 - 6 * (b ^ 2) + 11 * b - 6

If fa * fb > 0 Then
    MsgBox "Invalid interval!"
    Exit Sub
End If

Do While NumIter < MaxIter

    c = (a + b) / 2
    
fa = a ^ 3 - 6 * (a ^ 2) + 11 * a - 6
fc = c ^ 3 - 6 * (c ^ 2) + 11 * c - 6

    d = b - a
    
    NumIter = NumIter + 1
    
    Cells(NumIter + 6, 1).Value = NumIter
    Cells(NumIter + 6, 2).Value = a
    Cells(NumIter + 6, 3).Value = b
    Cells(NumIter + 6, 4).Value = c
    Cells(NumIter + 6, 5).Value = fa
    Cells(NumIter + 6, 6).Value = fc

    If d < Tol Then
        MsgBox "Root found: " & Round(c, 6)
        Exit Sub
    End If

    If fa * fc < 0 Then
        b = c
    Else
        a = c
    End If

Loop

MsgBox "Max iterations reached. Root ˜ " & Round(c, 6)

End Sub


Public Function BisectionMethod()

    Dim temp() As Variant
    
    Dim MaxIter As Integer
    Dim Tol As Double
    Dim a As Double, b As Double, c As Double
    Dim fa As Double, fb As Double, fc As Double
    
    Dim NumIter As Integer
    Dim d As Double

    a = InputBox("Enter lower bound (a): ")
    b = InputBox("Enter upper bound (b): ")
    Tol = InputBox("Enter tolerance: ")
    MaxIter = InputBox("Enter maximum number of iterations")
    

    ReDim temp(1 To MaxIter + 1, 1 To 3)
    
    NumIter = 0
    
    
    temp(1, 1) = "Iteration"
    temp(1, 2) = "Tolerance (b-a)"
    temp(1, 3) = "Root"
    
    
    fa = a ^ 3 - 6 * a ^ 2 + 11 * a - 6
    fb = b ^ 3 - 6 * b ^ 2 + 11 * b - 6


    If fa * fb > 0 Then
        MsgBox "Invalid interval!"
        Exit Function
    End If
    
    
    Do While NumIter < MaxIter
        

        c = (a + b) / 2
        
    
        fa = a ^ 3 - 6 * a ^ 2 + 11 * a - 6
        fc = c ^ 3 - 6 * c ^ 2 + 11 * c - 6
        
    
        d = b - a
        
        NumIter = NumIter + 1
        
    
        temp(NumIter + 1, 1) = NumIter
        temp(NumIter + 1, 2) = d
        temp(NumIter + 1, 3) = c
        
    
        If d < Tol Then
            Exit Do
        End If
 
        If fa * fc < 0 Then
            b = c
        Else
            a = c
        End If
        
    Loop
    
    BisectionMethod = temp

End Function



Private Sub BisectionButton_Click()

    Dim a As Double, b As Double, c As Double
    Dim fa As Double, fb As Double, fc As Double
    Dim MaxIter As Integer, NumIter As Integer
    Dim Tol As Double, tolVal As Double

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    ' Clear sheet
    ws.Cells.Clear

    ' Delete old charts
    Dim obj As ChartObject
    For Each obj In ws.ChartObjects
        obj.Delete
    Next obj

    ' ===== INPUTS =====
    a = Val(TextBoxA.Value)
    b = Val(TextBoxB.Value)
    MaxIter = Val(TextBoxMaxIter.Value)
    Tol = Val(TextBoxTol.Value)

    ' ===== HEADERS =====
    ws.Cells(6, 1) = "Iter"
    ws.Cells(6, 2) = "Root"
    ws.Cells(6, 3) = "Tolerance"

    NumIter = 0

    ' Initial function values
    fa = a ^ 3 - 6 * a ^ 2 + 11 * a - 6
    fb = b ^ 3 - 6 * b ^ 2 + 11 * b - 6

    If fa * fb > 0 Then
        MsgBox "Invalid interval!"
        Exit Sub
    End If

    ' ===== BISECTION LOOP =====
    Do While NumIter < MaxIter

        c = (a + b) / 2
        fc = c ^ 3 - 6 * c ^ 2 + 11 * c - 6

        tolVal = Abs(b - a)

        NumIter = NumIter + 1

        ws.Cells(NumIter + 6, 1) = NumIter
        ws.Cells(NumIter + 6, 2) = c
        ws.Cells(NumIter + 6, 3) = tolVal

        If tolVal < Tol Then Exit Do

        If fa * fc < 0 Then
            b = c
        Else
            a = c
        End If

    Loop

    ' ===== OUTPUT =====
    Label7.Caption = Round(c, 6)
    Label9.Caption = tolVal

' =========================
' GRAPH 1: ROOT
' =========================
    Dim chtObj1 As ChartObject
    Set chtObj1 = ws.ChartObjects.Add(Left:=200, Top:=200, Width:=250, Height:=200)

    With chtObj1.Chart
        .ChartType = xlLine
        .SeriesCollection.NewSeries
        .SeriesCollection(1).XValues = ws.Range(ws.Cells(7, 1), ws.Cells(NumIter + 6, 1))
        .SeriesCollection(1).Values = ws.Range(ws.Cells(7, 2), ws.Cells(NumIter + 6, 2))
        .SeriesCollection(1).Name = "Root"

        .HasTitle = True
        .ChartTitle.Text = "Root Convergence"

        .HasLegend = False

        .Axes(xlCategory).HasTitle = True
        .Axes(xlCategory).AxisTitle.Text = "Iteration"

        .Axes(xlValue).HasTitle = True
        .Axes(xlValue).AxisTitle.Text = "Root"

        .Axes(xlCategory).TickLabelSpacing = 1
    End With

' =========================
' GRAPH 2: TOLERANCE
' =========================
    Dim chtObj2 As ChartObject
    Set chtObj2 = ws.ChartObjects.Add(Left:=500, Top:=200, Width:=250, Height:=200)

    With chtObj2.Chart
        .ChartType = xlLine
        .SeriesCollection.NewSeries
        .SeriesCollection(1).XValues = ws.Range(ws.Cells(7, 1), ws.Cells(NumIter + 6, 1))
        .SeriesCollection(1).Values = ws.Range(ws.Cells(7, 3), ws.Cells(NumIter + 6, 3))
        .SeriesCollection(1).Name = "Tolerance"

        .HasTitle = True
        .ChartTitle.Text = "Tolerance Convergence"

        .HasLegend = False

        .Axes(xlCategory).HasTitle = True
        .Axes(xlCategory).AxisTitle.Text = "Iteration"

        .Axes(xlValue).HasTitle = True
        .Axes(xlValue).AxisTitle.Text = "Tolerance"

        .Axes(xlCategory).TickLabelSpacing = 1
    End With

End Sub










Post a Comment

0Comments
Post a Comment (0)