Write My Paper Button

WhatsApp Widget

Practical Session 2 – LOOPS and IF STATEMENTS – My Assignment Tutor

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 = 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

CLAIM YOUR 30% OFF TODAY

X
Don`t copy text!
WeCreativez WhatsApp Support
Our customer support team is here to answer your questions. Ask us anything!
???? Hi, how can I help?