Practical Session 2 – LOOPS and IF STATEMENTSIn this session, we will work through exercises on two key programming principles (usingPython): Repetition (for and while loops) and Conditionals (IF statements).You should be able to complete the lab sheet and answer the assessed questionwithin the allotted lab time (and are strongly encouraged to do so).Part A: Repetition and Different Types of Loop in PythonLet’s investigate solutions to non-linear equations using direct iteration: 𝑥𝑛+1 = 𝑔(𝑥𝑛). Inparticular, let’s revisit Q2 (a) off the numerical methods examples sheet:𝑥𝑛+1 = tan-1(2𝑥𝑛)with 𝑥0 = 1.0. To solve this we would plug in 𝑥0 to find 𝑥1, then plug in 𝑥1 to find 𝑥2, and soon. In other words, we would iterate, or keep “looping” through the equation.(i) Non-Deterministic loop – repeating until a criterion is metLet’s decide to keep iterating/looping until the difference between the old x value and new xvalue is really small: i.e. we keep looping while the quantity |𝑥𝑛+1 – 𝑥𝑛| > 𝑡𝑜𝑙𝑒𝑟𝑎𝑛𝑐𝑒, and westop when |𝑥𝑛+1 – 𝑥𝑛| ≤ 𝑡𝑜𝑙𝑒𝑟𝑎𝑛𝑐𝑒.In other words, we iterate WHILE |𝑥𝑛+1 – 𝑥𝑛| > 𝑡𝑜𝑙𝑒𝑟𝑎𝑛𝑐𝑒.The following program uses a WHILE loop to solve the equation from before. Read throughand understand this code before writing or downloading (see Blackboard) the Python scriptand running in Python.import math #importing maths functionschange = 1 #setting a large initial change valuex = 1 #our initial guess at the answertolerance = 1e-6 #our specified tolerance or accuracyn = 0 #starting value of an iteration counter nwhile change > tolerance: #iterate while condition holdsx_old = x #save old value of xx = math.atan(2*x) #get new value of xn = n + 1 #increase iteration counterprint(n,x) #print new n and x valueschange = abs(x_old – x) #work out change between old and new xExercise: Quickly investigate how the chosen tolerance value affects the number ofiterations needed and the accuracy of your answer. Make a note of your observations. Asmaller tolerance requires more iterations and longer run times. Regarding accuracy,a tolerance of 1e-4 (for example) does not (in general) guarantee accuracy in the 4thdecimal place (your 4th decimal place value could still change slightly in subsequentiterations). Generally, be safe and choose a tolerance small enough for you to beconfident in the accuracy of your answer.(ii) Deterministic loops – repeating a fixed number of timesThe following Python code solves the previous equation by doing the iterations (the loops) afixed number of times. We now use a for loop.You’ll notice use of a new command: range(1,10). This returns the integer sequence 1, 2,3,…., 8, 9 – but not 10!! The for loop then causes n to take each of the integer values one tonine in turn.Note, if we used range(10), then this would provide a sequence counting from zero tonine: 0, 1, 2,…9.Type this code into a Python script and run it yourself. Also provide appropriate comments.import math #x = 1 #for n in range(1,10): #x = math.atan(2*x) #print(n,x) #Exercise: Modify either of the above codes to solve the equation (see Q3, examples sheet)𝑒2𝑥 = 𝑥 + 2 → 𝑥𝑛+1 = 12 𝑙𝑛(𝑥𝑛 + 2)with a starting value of 𝑥0 = 0.5. Obtain an answer correct to four decimal places.(Hint: Natural logarithm, ln(x), is log(x) in Python). ANS:…0.4475………………………..Include X = 0.5*math.log(x+2.0) in one of above codes instead of X =math.ATAN(2.0*X) (and change starting x value).PART B(i): Solving ODEs using Euler’s MethodNow that we know how to iterate and repeat calculations in Python, we can go ahead andwrite code that uses Euler’s method to solve Ordinary Differential Equations.Let’s look at the following ODE (similar to Q14 on the numerical methods example sheet):𝑑𝑝𝑑𝑡 = 𝑡2with p=0 at t=0.As we have seen, using a forward difference formula for 𝑑𝑝𝑑𝑡we can re-write the above as:𝑝𝑛+1 = 𝑝𝑛 + ℎ𝑡𝑛2for some chosen step length (in time), h. From starting values 𝑝0 = 0 and 𝑡0 = 0, we caniterate over this equation to find p at future times t.The following code does this (and so solves the ODE) from t=0 up to the time t=1.0. p = 0time = 0h = 0.05# Initial pressure value# Initial time value# Chosen step length while time < 1.0: # Iterate while time is less than 1.p = p + h*time**2 # Update p using Euler’s methodtime = time + h # Update time by step-length hprint(format(time,”^-9.2f”),format(p,”^-9.4f”)) #print resultAside: You’ll notice use of the format command in the print statement – this helps makethe numbers printed look more readable. The various symbols and numbers informat(time,”^-9.2f”) tells Python to: Position all the printed time values as centrally as possible in space available (^) Only print the sign of the number if it is negative (-) Allow 9 spaces to contain the whole number (including sign, commas, decimal pointsetc) Allow 2 numbers after the decimal place (.) Specify that the numbers printed are floats (f) and have decimal points.Exercise(i) Read, download or type in this code and try to understand every line (ask if stuck!).(ii) Run the code; briefly investigate and comment on what happens when you change thesize of the step length, h.……Changing h changes the number of iterations done up to time t=1.0. A smaller h(smaller time steps) needs more steps forward (iterations) to reach the final time. Thisincreases computation time. However, it should be more accurate (see (iii) below).Notice that if you don’t format the output, your time values from Python also aren’tperfect (e.g. you may not finish exactly on 1.000000). This is due to something calledcomputer “round-off” error – small errors in the last few decimal places. With nondeterministic loops, these errors might mean you to stop one iteration later than whatyou want, but as long as we realise this has happened it is not a big issue.……(iii) The above ODE has an analytical solution given by:𝑝 =𝑡33Using this exact answer, find the error in p at t=0.5 for the following step-length sizes:h=0.05, 0.025, 0.0125. How does the error vary with h? Is this expected?………The exact answer is p=0.0416666 at t=0.5.For h=0.05 the code gives p=0.035625 at t=0.5 so error is 6.04e-3For h=0.025 the code gives p=0.03859 so error is 3.08e-3For h=0.0125 the code gives p=0.040117 so error is 1.55e-3As can be seen, if h is halved, the error is roughly halved. This is exactly what weexpect from a first order approximation like the Euler method (based on a forwarddifference)……………………………………………………………………………………………….PART B(ii): Solving ODEs using Libraries: Scipy (https://scipy.org/)Python has powerful and expansive scientific libraries available, such as Scipy. An importantlibrary within scipy is scipy.integrate, which provides functions to integrate ODEs (alsoknown as IVPs – Initial Value Problems) in the manner shown below.(Note: the scipy.integrate library requires we use “t” for time, and “y” for the dependentvariable, instead of “p” as in the previous example)import scipy.integrate #import the scipy integration librarydef rhs(t,y): return t**2 # define the right hand side (rhs) of# our ODE ie. t**2 in this examplesolution = scipy.integrate.solve_ivp(rhs,[0,1],[0], t_eval=[0,0.5,1]) print(solution.t)print(solution.y)#print the list of desired time values#print corresponding calculated y (or p) values Read, download and run the above code. Note that the solver stores values in solution,from which we can obtain one list containing our desired/stored time values, and another listcontaining the corresponding y values. Comment on which approach (this library or Euler’s)is more accurate (eg compare p (i.e. y) values at t=0.5, for example).Scipy solver more accurate, due to high-order time stepping schemes and othernumerical strategies beyond the scope of this course. For more info seehttps://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html#scipy.integrate.solve_ivpThe Scipy ODEsolver functionThe rhs of our ODE, asdefined just above (ie t**2)Range of time values,here from 0 to 1 inclusiveInitial y (or p) valueThe time values where you wantthe solution stored/printedPART C: Conditional Processing (IF Statements)The code below uses quite a harsh system to assign grades based on marks gained in anExam. It makes use of IF STATEMENTS.class_list = [“Steve”, “Bob”, “Sue”, “Danny”, “Isabella”]for name in class_list:print(“Enter mark of”, name)mark = input()mark = float(mark)if mark < 0:print(“Negative mark entered”)breakelif mark >= 70:grade = “A”else:grade = “F”print()print(“The grade of”, name, “is”, grade, end=”nn”)print(“Marks Entry Finished”)IF statements are quite useful for controlling and checking program flow, allowing you, forexample, to escape loops if certain criteria are met or errors occur.For example, in the previous code the break statement cause the code to escape the forloop, meaning the final print statement is the next thing to be executed before the codefinishes.Exercise(i) Run the program (download code from Blackboard). Test it with a couple of input marks,e.g. 40, 69, 70, -1.(ii) Swap break for continue and note the difference in the program behaviour.…break causes the program to exit the for-loop straightaway, whereas continuecauses the program to jump to the next iteration (next name) in the for loop…(iii) Improve the fairness of the program by including options for B and C grades according tomark ranges: 60≤B

- Assignment status: Already Solved By Our Experts
*(USA, AUS, UK & CA PhD. Writers)***CLICK HERE TO GET A PROFESSIONAL WRITER TO WORK ON THIS PAPER AND OTHER SIMILAR PAPERS, GET A NON PLAGIARIZED PAPER FROM OUR EXPERTS**

**NO PLAGIARISM**– CUSTOM PAPER