Phys102-Lecture01-11-10Fall.ppt

advertisement
Computational Lab in Physics: Part I
Introduction
Basics of Linux, Emacs & C++
Steven Kornreich
www.beachlook.com
Linux: http://www.linux.org/
C++: http://www.cplusplus.com/
Introduction, Using computers for a Physical
problem: Waves


A transverse wave has
mathematical model:
y=y0 + Asin(kx-wt + f)
2
Computers help to visualize:
eg. Using 2 1-D plots.
3
The parameters of the wave function:
A particular wave function
2
 2

y  y0  A sin 
x
t f 
T
 

2
 2

y  0  2 sin 
x
t  / 2
3
 4



Recall, the
displacement y
depends on x,t (it
is a 2-D function)
We represent it
here by 2 1-D
functions.


Space dependence
Time dependence
4
displacement
Visualizing a 1-D wave function moving
in time: a “Lego” plot of displacement of
the wave vs. x and t.
5
More complicated waves:
Visualizing waves in “Jaws”, Maui.
6
Objective of this course

Introduce the computing resources
available to you.





Get to know Linux/Unix
Get some Physics programming experience
Learn some useful numerical methods.
Become acquainted with commonly used tools,
such as ROOT.
Note:


you will not become an expert
you will know where to go find more information
in order to become one!
7
Linux user at Best Buy…
http://xkcd.com/272/
8
Introduction to Unix/Linux



You should be able to access all the
machines in P106, all have Linux as the
Operating System.
Look for an email from help@physics
First tasks:


log in (if you haven’t done so).
Change your password (if you haven’t done
so)

passwd : command to change a user’s
password.
9
Getting
help


“man pages”
On almost any command, can obtaing a “manual”
of usage by typing:











http://xkcd.com/456/
Ok, but what commands do I need?


man command
cat
ls
grep
tail
head
awk
sed
vi
….
And now you cry for help…
Word to the wise: learning unix can feel like
learning an archaic language… don’t despair!
10
Getting around using (gasp!) a
command line interface.

Open a terminal window in your
desktop: click on the terminal icon.


This will load an “xterm”: a terminal in
the X11 windows system.
You will be greeted by the Unix prompt.
[mcalderon@born ~]$
 Note: you can change your prompt. Look it
up in a UNIX book.


All commands are typed at the prompt,
producing a result.
11
The filesystem

Where are you when you log in?



The file system is a series of directories and
subdirectories


(or folders and subfolders)
Every user has an area all their own: their home
directory.



Typically, in your “home directory”
~ is shorthand for your home directory.
~mcalderon: my home directory
Syntax: ~username
To find where you are:

pwd : present working directory
[mcalderon@born ~]$ pwd
/home/mcalderon


I am in the directory called “mcalderon”,
which sits in the directory called “home”
12
Moving in the filesystem

To move to a different directory:


Two useful directories:



cd : change directory
“.” : the present working directory
“..” : the directory immediately above
the present working directory
Seeing what is in a directory:

ls : list the contents of a directory
13
Options or flags for commands


Commands can take
options that modify
their behavior
Example

ls , or ls . : lists the
current working
directory
[mcalderon@born ~]$ ls
Desktop location.of.fonts
math.5.2.fonts.tar phy102

With options:
[mcalderon@born ~]$ ls –l
total 26052
drwxr-xr-x 2 mcalderon mcalderon
4096 Jul 26 10:14
Desktop
-rw-r--r-- 1 mcalderon mcalderon
53 May 4 16:33
location.of.fonts
-rw-r--r-- 1 mcalderon mcalderon 26613760 May 4 16:31
math.5.2.fonts.tar
drwxrwxr-x 3 mcalderon mcalderon
4096 Oct 1 12:32
phy102



Commonly used options for ls:
ls –a : list all, including hidden
ls –l : as above, gives
read/write/execute permissions,
size, owner, date of last
modification.
14
Some useful Unix commands
cat
chmod
cd
cp
date
echo
ftp
grep
head
ls
lpr
more
mkdir
mv
pwd
rm
rmdir
passwd
ssh
sed
setenv
sort
tail
tar
wc
exit
catenates the contents of files and displays them
change file permissions
change directory
copy a file
display date
echo (to the screen) an argument, eg. an env. variable
file transfer protocol
searches for a string in a file
displays the first lines of a file
lists the names of files in a directory
send a file to the line printer
displays a file a screenful at a time
create directory
moving (and renaming) files
see the present working directory
remove a file
remove a directory
used to change passwords
opens a secure shell in a remote host
edits files in a batch, noninteractively.
set an environment variable
sort file
displays the last lines of a file
create an archive, add or extract files to it
count characters, words, lines
for logging out (also logout, ctrl-D)
15
File permissions
 When using ls –l, the permissions are displayed
[mcalderon@born ~]$ ls –l
total 26052
drwxr-xr-x 2 mcalderon mcalderon
4096 Jul 26 10:14 Desktop
-rw-r--r-- 1 mcalderon mcalderon
53 May 4 16:33 location.of.fonts

The “-rw-r--r--” describe the file permissions:
 first character




d : directory
- : file
l : soft link
Next three characters, user permissions:

r: read, w:write, x:execute
Next three characters: group permissions
 Next three characters: “world” permissions
Setting permissions: chmod command
chmod a+r : add read permissions to “a”ll.
Use “man chmod” to get all the details.




16
Further reading:

“A practical guide to the UNIX
system”, Mark G. Sobell, 3d Ed.
Addison Wesley, 1995.
17
The emacs editor

Emacs :



emacs is useful for editing ascii text, but
can do many more things.
It recognizes various types of files, e.g.:





“Emacs is the extensible, customizable, selfdocumenting real-time display editor”.
C++ source files
html source files
tex source files
Advantage: It is free.
Available with all UNIX distributions.
18
Using emacs

to invoke: type “emacs” at the unix
prompt.


Will yield a blank emacs “buffer”
can also type “emacs someFile”, will open
emacs with the specified loaded in the emacs
buffer.
 buffer: a copy of the file on disk.






Editing in emacs : editing the buffer copy.
Saving the file: overwrites the file on disk with the
contents of the buffer.
Saving a file: click on “Save” or ctrl-x,ctrl-s
Most command keystrokes use
C : ctrl key, or
M : meta key (Esc in our case).
19
Using emacs, cont.

Can open several files in the same window:



switch between them in the “buffers” tab.
ctrl-x ctrl-f
Can cut, paste, as usual, but command keystrokes are
different:





cut: ctrl-w
cut a line (“kill” in emacs) : ctrl-k
paste (“yank” in emacs) : ctrl-y
go to end of line: ctrl-e
go to the beginning of the line: ctrl-a


Note, ctrl-e and ctrl-a are also valid at the unix prompt.
Copying, pasting with the mouse:


Highlight area to copy by dragging mouse over the area
with left button down
Release left button, place cursor in position where text
should appear, press middle button.
20
More commands:
Command
Keystroke
Description
forward-word
M-f
Move forward past one word.
search-word
C-s
Search a word in the buffer.
undo
C-/
Undo last change, and prior changes if pressed repeatedly.
keyboard-quit
C-g
Abort the current command.
fill-paragraph
M-q
Wrap text in ("fill") a paragraph.
find-file
C-x C-f Visit a file (you specify the name) in its own buffer.
save-buffer
C-x C-s Save the current editor buffer in its visited file.
save-with-newname
C-x C-w Save the current editor buffer with name you
specify.
save-buffers-kill-emacs
C-x C-c Offer to save changes, then exit Emacs.
set-marker
C-[space] Set a marker from where to cut or copy.
cut
C-w
Cut all text between the marker and the cursor.
copy
M-w
Copy all text between the marker and the cursor.
paste
C-y
Paste text from the emacs clipboard
kill buffer
C-x k
Kill the current buffer
Suspend program C-z
Suspend the program
21
emacs: Useful tidbits…

killing, yanking rectangles





In C++ mode:



Useful for cutting/pasting a block of text
Comes in handy for code arranged in blocks.
esc-x yank-rectangle, esc-x kill-rectangle, or
ctrl-x r y, ctrl-x r k
can comment/uncomment regions
can compile code in emacs directly
Many more…
22
More information…

Emacs homepage from gnu project


Wikipedia entry


http://www.gnu.org/software/emacs/
http://en.wikipedia.org/wiki/Emacs
Emacs tutorial through emacs:


look under the “Help” tab
or ctrl-h t
23
C++ Programming

A tutorial:


http://www.cplusplus.com/doc/tutorial/
We will follow the first example
given in that tutorial

Most C++ books start with this
example.
24
The first C++ program: the Hello World
Example
// my first program in C++
#include <iostream>
using namespace std;
int main () {
cout << "Hello World!” << endl;
return 0;
}
25
Compiling the program.

Compiling:

g++ hellomain.cc –o hello_world
 Simple Usage: g++ [source] –o [name-ofexecutable]
 Some options:

-c
Compile only (creates object file .o)
-o filename
compile and link, name the executable “filename”
-Ox
optimization level x, x={0,1,2,3}
-L
library path for linker
-l
library name for linker
-I
path for include files
-g
produces a debugging version
Try “man g++” to see the man pages.
26
Running the program

To execute, invoke the program
name:



./hello_world
The “./” are needed if by default you do
not have the current working directory
as part of your path.
Output:
[mcalderon@born exercises]$ ./hello_world
Hello World!
27
Comments (very important!)

// my first program in C++




Lines beginning with two slash signs (//) are
considered comments.
Do not have any effect on the behavior of the
program.
Use them to include short explanations or
observations within the source code.
In this case, line is a brief description of what
our program is.
 Good style:


Add Author, date, description.
Add small comment blocks to describe aim of
parts of code.
28
Preprocessor directives

#include <iostream>


Lines beginning with a pound sign (#) are
directives for the preprocessor.
Not regular code lines, rather indications for the
compiler's preprocessor.
In this case, #include <iostream>
tells the preprocessor to include the iostream standard
file.


What is iostream?



In general: include files whose functionality is
going to be used later in the program.


“input-output stream”
includes the declarations of the basic standard inputoutput library in C++
in this case, “cout” and “endl”.
In lab, try compiling the program without this
line. What happens?
29
Namespaces

using namespace std;



All elements of the standard C++ library are
declared within a namespace.
The name of this namespace is std.
How do we access its functionality?
 declare with this expression that we will be
using these entities.
 This line is frequent in C++ programs that use
the standard library.
 it will be included in most of the source codes
included in this course.
30
The Hello World Example, another
way: without “using namespace std”.
// my first program in C++
#include <iostream>
int main () {
std::cout << "Hello World!” << std::endl;
return 0;
}
31
The main function

int main ()



This line corresponds to the beginning of the definition of
the main function.
The main function: point by where all C++ programs
start their execution.
Location within the source code is irrelevant:







Other functions with other names defined before or after it
don’t matter.
The instructions contained in main() will always be the
first ones to be executed in any C++ program.
It is essential that all C++ programs have a main
function.
The word “main” is followed in the code by a pair of
parentheses “()”: this means it is a function declaration.
Optionally, these parentheses may enclose a list of
parameters within them.
The body of a function is enclosed in the { } that appear
after ().
The code inside { } specifies what that function will do. 32
C++ statements
cout << "Hello World!“ << endl;
 This line is a C++ statement: a simple or compound expression
that can actually produce some effect.


Meaning of the entire statement:



In our example, this statement is only one producing a visible effect.
insert a sequence of characters (in this case the “Hello World!” sequence
of characters and the “endline” directive ) into the standard output
stream.
cout: represents the standard output stream in C++
standard output: usually the screen (but does not have to be).


cout is declared in the iostream standard file within the std
namespace.
Therefore, we needed to:




Statements end with a semicolon character (;).
Semicolon:



include that specific file, iostream, where std::cout is defined.
declare that we were going to use this specific namespace.
marks the end of the statements
Must be included at the end of all expression statements in all C++
programs.
Common syntax errors: forget to include a semicolon.
33
Return statements.

return 0;



The return statement causes the main function
to finish.
return may be followed by a return code (in
our example is followed by the return code 0).
 A return code of 0 for the main function is
generally interpreted as: “the program worked
as expected without any errors during its
execution”.
This is the most usual way to end a C++
console program.
34
Doing calculations…
sin(x), for 0<x<2, in steps of /6
//
// A program to test the math functions
//
#include <cmath>
#include <iostream>
using std::cout;
using std::endl;
int main() {
// We will do a loop from x=0 to x=2pi in steps of pi/6
// for each part of the loop, we will print to the standard output
// the result of evaluating the function sin(x).
}
for (float x=0.0; x<2*M_PI; x+=M_PI/6.) {
cout << "sin(" << x << ") = " << sin(x) << endl;
}
return 0;
35
“For” loops

for (float x=0.0; x<2*M_PI; x+=M_PI/6.)


Other types of loops



Syntax: for (initial condition; condition to end loop;
change in variable, usually increase or decrease)
while(condition) { }
Look these up in a C++ reference.
In our example:


initial condition: x=0
condition to end loop: x<2.


Note: in our linux version of C++, M_PI is defined in the math.h
header (included by the cmath header) to store p.
# define M_PI
3.14159265358979323846 /* pi */


If you grep for M_PI in the math.h header, how many definitions
do you see?
Change in variable: increase x by /6 every pass.

the “+=“ operator means: increment the variable on the lhs by
the rhs and store the result in the same lhs variable.

In other words: x+=M_PI/6. is equivalent to x=x+M_PI/6.
36
Types, assignment and constructors

float x=0.0;

This statement does several things:

“float”: specifies we will use a floating point variable, or a “type”.






float x : declares a variable called x of type “float”.
x = 0.0 : assigns to the variable x the value 0.0.
“=“ : called the assignment operator
Other ways to declare float variables.



float x(0.0);
This uses a function called the “constructor”.
Constructor:




Other types:
 int : integer
 variations: bool (2-bit), char (4-bit), short, int, long, long long. The
size of these is compiler dependent.
 double : a double precision floating point variable.
What happens if x is a double instead of a float?
function invoked whenever any type is declared.
sets aside the memory necessary to store the object or type.
If needed, initializes the memory with either a default value, or with values
given to the constructor function.
What is the difference between these three statements?



float x;
float x(0.0);
float x = 0.0;
37
Homework, Chapter 3 Exercises

Homework 1 (Chapter 3)





(7) Write a program to calculate the square root of a
given number.
(8) Write a program to create the area of a rectangle.
Write the program in such a way that it asks you for
input of the two sides and gives you the area as output.
(9) Modify your program such that in case you input two
equal sides, it will give you the radius of the outscribing
circle.
Read Section 3.9 on machine precision
To hand in to smartsite:



Practice: Exercises 1-6 are useful to do to practice
using linux, navigating the filesystem,
creating/deleting files, and learn using some useful
unix commands
38
Due next week, at the same time of class.


One program for 3.7.
One program that does bothe 3.8, 3.9.
Write a program that displays the numbers you get when you
turn on the bits of an int one by one, and show that you can’t
use 33 bits. Hint: use the bit-shift operator << and a for loop.
Download