0% found this document useful (0 votes)
106 views37 pages

Computational Lab in Physics: Part I Basics of Linux, Emacs & C++

The document provides an introduction to using computational tools like Linux, Emacs, and C++ for physics problems. It discusses using computers to model and visualize waves through mathematical functions and 2D plots. It also outlines the objectives of the course to introduce computing resources and useful numerical methods while not making students experts. The document then provides tutorials on basic Linux commands, file navigation, and the Emacs text editor.

Uploaded by

benefit187
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views37 pages

Computational Lab in Physics: Part I Basics of Linux, Emacs & C++

The document provides an introduction to using computational tools like Linux, Emacs, and C++ for physics problems. It discusses using computers to model and visualize waves through mathematical functions and 2D plots. It also outlines the objectives of the course to introduce computing resources and useful numerical methods while not making students experts. The document then provides tutorials on basic Linux commands, file navigation, and the Emacs text editor.

Uploaded by

benefit187
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

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-ωt + φ)

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  
  T 
 2 2 
y  0  2 sin  x t  / 2
 4 3 
 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
Visualizing a 1-D wave function moving
in time: a “Lego” plot of displacement
of the wave vs. x and t.
displacement

tim
e

p ace
s
5
More complicated waves:
Visualizing waves in “Jaws”, Maui.

6
Objective of this course
 Introduce the computing resources
available to you.
 Get to know UNIX
 Get some 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
Introduction to Unix/Linux
 You should be able to access all the
machines in P106, all have Linux as
the Operating System.
 First tasks:
 login (if you haven’t done so).
 Change your password (if you haven’t
done so)
 passwd : command to change a user’s
password.

8
Getting help
 “man pages”
 On almost any command, can obtaing a “manual” of usage by
typing:
 man command
 Ok, but what commands do I need?
 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!

9
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.
 Allcommands are typed at the prompt,
producing a result.

10
The filesystem
 Where are you when you log in?
 Typically, in your “home directory”
 ~ is shorthand for your home directory.
 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.
 ~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”

11
Moving in the filesystem
 To move to a different directory:
 cd : change directory
 Two useful directories:
 “.” : 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

12
Options or flags for commands
 Commands can take
 With options:
[mcalderon@born ~]$ ls –l
options that modify total 26052
drwxr-xr-x 2 mcalderon mcalderon 4096 Jul 26 10:14
their behavior Desktop
-rw-r--r-- 1 mcalderon mcalderon 53 May 4 16:33
 Example location.of.fonts
-rw-r--r-- 1 mcalderon mcalderon 26613760 May 4 16:31
 ls , or ls . : lists the math.5.2.fonts.tar
drwxrwxr-x 3 mcalderon mcalderon 4096 Oct 1 12:32
current working phy102

directory
[mcalderon@born ~]$ ls  Commonly used options for ls:
Desktop location.of.fonts
math.5.2.fonts.tar phy102  ls –a : list all, including hidden
 ls –l : as above, gives
read/write/execute permissions,
size, owner, date of last
modification. 13
Some useful Unix commands
cat catenates the contents of files and displays them
chmod change file permissions
cd change directory
cp copy a file
date display date
echo echo (to the screen) an argument, eg. an env. variable
ftp file transfer protocol
grep searches for a string in a file
head displays the first lines of a file
ls lists the names of files in a directory
lpr send a file to the line printer
more displays a file a screenful at a time
mkdir create directory
mv moving (and renaming) files
pwd see the present working directory
rm remove a file
rmdir remove a directory
passwd used to change passwords
ssh opens a secure shell in a remote host
sed edits files in a batch, noninteractively.
setenv set an environment variable
sort sort file
tail displays the last lines of a file
tar create an archive, add or extract files to it
wc count characters, words, lines 14
exit for logging out (also logout, ctrl-D)
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. 15
Further reading:
 “A practical guide to the UNIX
system”, Mark G. Sobell, 3d Ed.
Addison Wesley, 1995.

16
The emacs editor
 Emacs :
 “Emacs is the extensible, customizable, self-
documenting real-time display editor”.
 emacs is useful for editing ascii text, but
can do many more things.
 It recognizes various types of files, e.g.:
 C++ source files
 html source files
 tex source files
 Advantage: It is free.
 Available with all UNIX distributions.

17
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).

18
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.

19
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

20
emacs: Useful tidbits…
 killing, yanking rectangles
 Useful for cutting/pasting a block of
text
 Comes in handy for code arranged in
blocks.
 In C++ mode:
 can comment/uncomment regions
 can compile code in emacs directly

 Many more…

21
More information…
 Emacs homepage from gnu project
 http://www.gnu.org/software/emacs/

 Wikipedia entry
 http://en.wikipedia.org/wiki/Emacs

 Emacs tutorial through emacs:


 look under the “Help” tab
 or ctrl-h t

22
C++ Programming
 A tutorial:
 http://www.cplusplus.com/doc/tutorial/

 We will follow the first example


given in that tutorial
 MostC++ books start with this
example.

23
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;
}

24
Compiling the program.
 Compiling:
 g++ hellomain.cc –o hello_world
 Simple Usage: g++ [source] –o [name-of-
executable]
 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. 25


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!

26
Comments
 // 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.

27
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?
 “input-output stream”
 includes the declarations of the basic standard input-output
library in C++
 In general: include files whose functionality is going to be
used later in the program.
 in this case, “cout” and “endl”.
 In lab, try compiling the program without this line. What
happens?

28
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.

29
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;
}
30
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.
31
C++ statements
cout << "Hello World!“ << endl;
 This line is a C++ statement: a simple or compound expression
that can actually produce some effect.
 In our example, this statement is only one producing a visible effect.
 cout: represents the standard output stream in C++,
 Meaning of the entire statement:
 insert a sequence of characters (in this case the “Hello World!” sequence
of characters and the “endline” directive ) into the standard output stream.
 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:
 include that specific file, iostream, where std::cout is defined.
 declare that we were going to use this specific namespace.
 Statements end with a semicolon character (;).
 Semicolon:
 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.
32
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.

33
Doing calculations…
//
// 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 sin(x).

for (float x=0.0; x<2*M_PI; x+=M_PI/6.) {


cout << "sin(" << x << ") = " << sin(x) << endl;
}
return 0;
}
34
“For” loops
 for (float x=0.0; x<2*M_PI; x+=M_PI/6.)
 Syntax: for (initial condition; condition to end loop; change in
variable, usually increase or decrease)
 Other types of loops
 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 p/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.

35
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”.
 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 x is a double instead of a float?
 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:
 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;

36
Homework, Chapter 5 Exercises
 First thing!!
 In your home directory make a subdirectory called
“phy102homework”
 all lower case
 In that subdirectory, create several subdirectories called
“hwk1”, “hwk2”, etc.
 Place the files for each homework in the appropriate
subdirectory.
 Make sure all these directories and source files are set to
be world readable., and directories world executable.
 Assignments
 (1) loop to print squares
 (2) loop to do Fibonacci sequence
 (6) loop to calculate factorials, difference btw int/float
 put all source files in the hwk1 directory
 Due next week, at the same time of class.
37

You might also like