Lecture 5 – Iterative Solutions

Introduction

Iterative techniques are used all the time in engineering. Simple trial and error calculation could be considered an iterative technique if you use logic to burrow down to the correct answer as shown in this video.

More formal techniques

Using the video above we can see doing this by hand, but we would like to have the computer do the iterations. Shown is putting the iterations into code.

Example

From the video you were able to see one method for the solution of an equation using an iterative approach. Shown is a more robust method for developing a solution to the same problem. Also this has a plot of the solution iterating onto the correct solution. The function TimeToVoltage applies an iterative technique where it uses the function CapacitorChargingVoltage as the calculation function.

import math
import matplotlib.pyplot as plt
print("RC Circuit Example")
print("Switch closed at t=0, opened at at time specified")
v = float(input("Input Voltage (v): "))
r = float(input("Input Resistance (Ohms): ")) 
c = float(input("Input capacitance(Farads): "))
t = float(input("Input time at which switch is opened (sec): "))

def CapacitorChargingVoltage(v, r, c, t):
   return v*(1 - math.pow(math.e, -t/(r*c)))

def CapacitorDischargeVoltage(v,r,c,t):
   return math.pow(math.e, -t/(r*c))

print(CapacitorChargingVoltage(v,r,c,t))

def PlotCharging(v, r, c, t):
   xp = []
   yp = []
   for i in range(0,10):
      x = i * t / 10.0
      xp.append(x)
      yp.append(CapacitorChargingVoltage(v,r,c,x))
   plt.plot(xp,yp)
   return plt.plot(xp,yp)

def TimeToVoltage(vf, vb, r, c ):
   xaxis = []
   guesses = []
   i = 1
   error = 1
   accuracy = 0.001
   increment = 0.1
   ts = 0
   sign = 1
   while (error > accuracy):
# vf - voltage we are trying to find
# va - voltage calculated at depth
      va = CapacitorChargingVoltage(vb, r, c, ts)
      xaxis.append(++i)
      guesses.append(va)
      if (vf > va):
         ts = ts + increment
# check to see if direction has changed
         if (sign == -1):
            sign = 1
            increment = increment/2
      else:
         ts = ts - increment
# check to see if direction has changed
         if (sign == 1):
            sign = -1
            increment = increment/2
      i = i + 1 
      error = abs(vf - va)
   plt.plot(xaxis,guesses) 
   return ts

print (TimeToVoltage(.5*v, v, r ,c))