Data Analysis, Practical Basics - Engineering - , Study notes of Engineering Physics

Physics / Astrophysics Laboratory -Programming

Typology: Study notes

2010/2011

Uploaded on 09/08/2011

russel85
russel85 🇬🇧

4.6

(5)

285 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Physics/Astrophysics Laboratory - Programming
INTRODUCTION
This part of the course is a simple introduction to the most elementary aspects
algorithms and programming. In doing this we’re going to make use of the QBASIC.
While this is too simple a programming language for complex scientific calculations if
you make an error in your typing QBASIC should highlight that error when you
attempt to press return at the end of the line. Therefore, BASIC is a simple first
programming language to learn and test algorithms to solve problems in
Physics/Maths. QBasic.exe (executable) is located in the folder “Physics\Qbasic”
on the Desktop.
In order to start the program either double click on the QBASIC icon in Windows.
In the following there are various programs to type in etc., when you have typed in
your program, you’ll want to run it. This is done by clicking on Run at the top of the
screen and selecting Start from the drop down menu. In the following programs you
will note that they always start with a cls and finish with an end. The former is simply
a command in QBASIC to clear the screen at the start of the program and the latter
is just a command which indicates the end of the program. Okay let’s begin.
BASIC: Worksheet 1
A FIRST PROGRAM
Let us get started straight away by typing in a complete program as follows.
Rem program to solve a quadratic equation
cls
input "Type in a,b,c "; a,b,c
let disc = b^2 - 4*a*c
let disc = sqr(disc)
let x1 = (-b + disc) /(2*a)
let x2 = (-b - disc)/(2*a)
print "Solutions are "; x1,x2
end
If you make mistakes in typing your program, edit it using the mouse or arrow keys
and the Backspace key. Usual editing features such as Cut and Paste are also
available using the Edit menu.
This example illustrates some fundamental features of BASIC. It is written as a
series of lines, called statements, each introduced by a keyword. The computer
starts at the top of a program and goes through the statements one by one, doing
what the statements tell it to. Anything on a line following REM does not form part of
the statement: it is treated as a comment, and you may put comments freely in your
programs to help you understand them.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Data Analysis, Practical Basics - Engineering - and more Study notes Engineering Physics in PDF only on Docsity!

Physics/Astrophysics Laboratory - Programming

INTRODUCTION

This part of the course is a simple introduction to the most elementary aspects algorithms and programming. In doing this we’re going to make use of the QBASIC. While this is too simple a programming language for complex scientific calculations if you make an error in your typing QBASIC should highlight that error when you attempt to press return at the end of the line. Therefore, BASIC is a simple first programming language to learn and test algorithms to solve problems in Physics/Maths. QBasic.exe (executable) is located in the folder “Physics \ Qbasic” on the Desktop.

In order to start the program either double click on the QBASIC icon in Windows. In the following there are various programs to type in etc., when you have typed in your program, you’ll want to run it. This is done by clicking on Run at the top of the screen and selecting Start from the drop down menu. In the following programs you will note that they always start with a cls and finish with an end. The former is simply a command in QBASIC to clear the screen at the start of the program and the latter is just a command which indicates the end of the program. Okay let’s begin.

BASIC: Worksheet 1

A FIRST PROGRAM

Let us get started straight away by typing in a complete program as follows.

Rem program to solve a quadratic equation cls input "Type in a,b,c "; a,b,c let disc = b^2 - 4ac let disc = sqr(disc) let x1 = (-b + disc) /(2a) let x2 = (-b - disc)/(2a) print "Solutions are "; x1,x end

If you make mistakes in typing your program, edit it using the mouse or arrow keys and the Backspace key. Usual editing features such as Cut and Paste are also available using the Edit menu.

This example illustrates some fundamental features of BASIC. It is written as a series of lines, called statements, each introduced by a keyword. The computer starts at the top of a program and goes through the statements one by one, doing what the statements tell it to. Anything on a line following REM does not form part of the statement: it is treated as a comment, and you may put comments freely in your programs to help you understand them.

The most important concept for you to grasp is that of a variable. The quantities a, b, c, disc, x1, x2 in the above program are numerical variables. Think of the memory of the computer as a series of boxes, each of which can contain one number. Whenever you introduce a new variable name in your program, it will be attached to one of the boxes, and thereafter in your program the variable name will refer to the value stored in the box. By the way, variable names can be almost anything you like, providing they start with an alphabetic character. Always try and give variables a meaningful name.

Variables can be used, together with constants (numbers) and operators to make expressions. An example of an expression in the above program is b^2 - 4ac. When BASIC encounters an expression, it works out its value using the current values of the variables. The mathematical operators are +, -, * (multiply), 1 (divide) and ^ (raise to the power). As in the above program, brackets may be used to make the mathematical meaning of an expression unambiguous.

The let statements assign the value of an expression to a variable. This means the expression on the right hand side of the equals sign is evaluated, and the resulting value is put into the variable on the left hand side (replacing any value that may already be there).

Another way to give variables a value is by means of the input statement. The best way to find out how this works is to try it. So, first think up a test case: a quadratic equation whose solution you know. Then run the program (click on Start in the Run menu), do what it asks and see if you get the right answer. If so, it is a good idea to save the program, giving it a suitable name (click on Save As in the File menu and use drive S:).

In order to write a computer program to solve a particular problem, one has to break the method of solution down into a series of sequential steps. This is called an algorithm. It is important that you follow through the given program step-by-step to make sure you understand how it solves the quadratic equation problem. When you have done this, it should be clear to you what sqr(disc), in the fourth line of the program means. The sqr is an example of a built-in function, and disc is its argument.

Function arguments can be expressions, as well as variables. Use this fact to modify the program to eliminate the third line. You can use Cut in the Edit menu to delete text that you have selected with the mouse. Check that the program still works properly.

MORE ON CONSTANTS, VARIABLES AND EXPRESSIONS

Try the following which illustrate some points about expressions. Make sure you understand what point is being made in each case. Type in and run the following

cls print 6+10/ end

Write a program that will take the values of  (in degrees) and v (in m/s) as inputs, and output the range R. Take g = 9. 8m/s. Use your program to investigate how R varies with 0 for a fixed value of v. For what value of  is R a maximum? Don't forget to save your program.

DECISIONS, DECISIONS

Get back the quadratic equation program (click on Open on the File menu), make up some sets of a,b,c values and try it out. What happens if you try to solve a quadratic equation which does not have real roots?

To get around this problem, modify your program so it appears as follows

Rem program to solve a quadratic equation cls input "Type in a,b,c"; a,b,c let disc = b^2 - 4ac if disc >= 0 then let disc = sqr(disc) let x1 = (-b + disc) / (2a) let x2 = (-b - disc) / (2a) print "Solutions are ";x1,x else print "Error: no real roots" end if end

Problem 1.

Modify the above program to print out the roots in the case where they are complex. (BASIC has no complex variable type: you will need to handle the real and imaginary parts separately.) Also make it handle the case a=0 correctly. Test and then save the new version.

In the absence of any control structures a program, when run, starts at the first statement and obeys the following statements one-by-one until the end is reached. We have just seen an example of a control structure, if.. else ... end if. Following the if is a logical expression, i.e. something which evaluates to either true or false. If the result is true, the then branch is obeyed: if false, the else branch is obeyed. Then the program continues with the statement after the end if. The else branch may be omitted if it is not required. Logical expressions are made using the relational operators >; <; = ; >= (greater than or equals); <= (less than or equals); <> (not equal to). With strings, the order is alphabetical. Logical conditions may be joined with and and or, or negated with not. Clear the quadratic equation program, and try this little program

cls if 2+2 = 4 and not 3+3 > 7 then

print "Brilliant" end if end

and this one

cls let six$ = "six" let seven$ = "seven" if seven$ < six$ then print "Alphabetically ";seven$;" is before ";six$ end if end

LOOPING

Another important control structure is the for .. next loop. Try this program

cls print "Table of square roots" for i = 1 to 10 print i, sqr(i) next i end

The loop is obeyed repeatedly with successive values of i. Modify the program so it prints a table of cube roots. It is also possible to include a step size:

cls pi = 3. for degrees = 0 to 90 step 5 radians = pi*degrees/ print degrees, radians, sin(radians) next degrees end

The for .. next loop repeats a specific number of times. We can also have loops which repeat depending on a logical condition. A common case is to continue input until a marker value is reached

cls do while name$ <> "stop" and name$ <> "STOP" input "What is your name? "; name$ print "Hello ";name$ loop end

Actually, this does not do quite what we want. We can use another version of the do loop, which tests at the end rather than the beginning.

where the notation 〈^ âŒȘ^ represents the mean (average) of all the values of A. First show algebraically that

√〈 âŒȘ 〈 âŒȘ

This is a more convenient form for computer analysis (why?). Now modify the above program so that it also calculates and prints the standard deviation of the set of numbers.

Problem 2.

Calculate the value of using the random number generator (ran) used in problem 2.1(Monte Carlo Simulation).

BASIC: Worksheet 3

MAXIMUM AND MINIMUM VALUES

The following algorithm will find the maximum and minimum of a set of n numbers read from the keyboard

input "n, and first value? "; n,x let maximum = x let minimum = x for i = 2 to n input "Next value? "; x if x > maximum then let maximum = x if x < minimum then let minimum = x next i

Make sure you understand this algorithm, then test it thoroughly. Generate 100 random numbers, and find the largest and smallest. Repeat with 1000 numbers. Is this what you expect?

TESTING FOR CONVERGENCE

The series

is a convergent series. The following algorithm sums this series until terms are less than a certain tolerance.

input "Enter value for tolerance: "; tolerance do let i = i + 1 let term = 1 / i^ let sum = sum + term

loop until abs(term) < tolerance

The function abs returns the absolute value of a number. It is not strictly necessary in this case, since all the terms are positive, but it is usually included in convergence tests since terms may often be negative. To make this algorithm into a complete program, input the tolerance, and print out the final result and the number of terms needed to reach it. Test using several values of the tolerance.

Problem 3.

Two possible series which can be used to calculate p are

and

Program both these, and find which converges most rapidly. Since you know the correct value for the sum, you can test on the actual error, rather than the size of the terms. What difference does this make?

Problem 3.

Write a program which uses the Taylor series expansion to calculate exp(x)

In this case you will need to start by developing an algorithm which enables each term of the series to be expressed in terms of the previous one. Carry on the summation until some suitable convergence criterion has been satisfied. Compare your results with those from the built-in exp function (which does not use the same method!) What happens for large positive and negative values of x?

BASIC: Worksheet 4

ARRAYS

The BASIC statement

DIM X(10)

sets up an array of 10 elements, X(I), X(2),... X(10), each of which can hold a number. Each element can be referred to using either a constant index, e.g. X(8), or by using a variable as index, e.g. X(K). In the latter case the element selected will be the one whose index is the current value of the variable K. Clearly we ought to

let xn = xt else let xp = xt end if loop until abs (xp - xn) < tolerance print xn, xp, f(xn), f(xp) end

This code will execute the bisection method or algorithm for the function f(x). However we haven't as yet defined the function f(x), how do we do this? Click on Edit and then click on New Functions. You will be prompted for the name of your function, in this case just call it f, then a new editor window will appear. Type in the following code (some of it will already be there);

function f (x) f = exp(x) - 3 * x end function

Then save your program to diskette. In order to switch editing windows between this function and the main program code you typed in earlier go to View and click on Subs. A menu will appear from which you can select the main program by the name you saved it under to the diskette or the subroutine by the name f. Click on whichever one you want to edit and then click on Edit in active window.

If you go back to the main code you will find that a new line has been added at the top, a declare function line. You could have typed this line in yourself if you had so wished, although the QBASIC interpreter will do it for you if you use the New function selection in edit.

Problem 5.

Use the above program to find the solutions of the equation

As a hint try xn=1 and xp=5 at first. There is more than one solution. Try searching around to find the second solution. Is the order in which you enter xn and xp important? [Answer is yes, try seeing if you can work out the rule.]

Problem 5.

Find the solutions of the equation (how many should there be?)

What do you need to change from the previous code to find the solution of this equation? Do you need to change all of the code or just one part?