ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 17.04.2021

Просмотров: 3710

Скачиваний: 3

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.
background image

Introduction to Python for Science, Release 0.9.23

log function

log

from NumPy. You could write

from

numpy

import

log

To use the

log

function in a script, you would write

a

=

log(

5

)

which would assign the value

1.6094379124341003

to the variable

a

. If you wanted

to import the three functions,

log

,

sin

, and

cos

, you would write

from

numpy

import

log, sin, cos

and would similarly use them without an “

np.

” prefix. In general, we do not recommend

using the the

from

module

import ...

way of importing functions. When reading

code, t makes it harder to determine from which modules functions are imported, and can
lead to clashes between similarly named functions from different modules. Nevertheless,
you will see the form used in programs you encounter on the web and elsewhere so it is
important to understand the syntax.

2.10 Getting help: documentation in IPython

Help is never far away when you are running the IPython shell. To obtain information
on any valid Python or NumPy function, and many MatPlotLib functions, simply type

help(

function

)

, as illustrated here

In [1]:

help(

range

)

range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.

range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults

to 0.

When step is given, it specifies the increment (or

decrement).

For example, range(4) returns [0, 1, 2, 3].

The

end point is omitted! These are exactly the valid indices for a

list of 4 elements.

Often, the information provided can be quite extensive and you might find it useful to
clear the IPython window with the

clear

command so you can easily scroll back to find

the beginning of the documentation. You may have also noticed that when you type the
name of a function plus the opening parenthesis, IPython displays a window showing the
first dozen lines or so of the documentation on that function.

2.10. Getting help: documentation in IPython

25


background image

Introduction to Python for Science, Release 0.9.23

2.11 Programming is a detail-oriented activity

Now that you have a little experience with Python and computer programming, it’s time
for an important reminder:

Programming is a detail-oriented activity

. To be good at

computer programming, to avoid frustration when programming, you must pay attention
to details. A misplaced or forgotten comma or colon can keep your code from working.
Note that I did not say it can “keep your code from working

well

”; it can keep your code

from working at all! Worse still, little errors can make your code give erroneous answers,
where your code appears to work, but in fact does not! So pay attention to the details!

This raises a second point: sometimes your code will run but give the wrong answer
because of a programming error or because of a more subtle error in your algorithm. For
this reason, it is important to test your code to make sure it is behaving properly. Test it
to make sure it gives the correct answers for cases where you already know the correct
answer or where you have some independent means of checking it. Test it in limiting
cases, that is, for cases that are at the extremes of the sets of parameters you will employ.
Always test your code; this is a cardinal rule of programming.

26

Chapter 2. Launching Python


background image

Introduction to Python for Science, Release 0.9.23

2.12 Exercises

1. A ball is thrown vertically up in the air from a height

h

0

above the ground at an

initial velocity

v

0

. Its subsequent height

h

and velocity

v

are given by the equations

h

=

h

0

+

v

0

t

1
2

gt

2

v

=

v

0

gt

where

g

= 9

.

8

is the acceleration due to gravity in

m

/

s

2

. Write a script that finds

the height

h

and velocity

v

at a time

t

after the ball is thrown. Start the script by

setting

h

0

= 1

.

2

(meters) and

v

0

= 5

.

4

(m/s) and have your script print out the

values of height and velocity (see

Note about printing

). Then use the script to find

the height and velocity after 0.5 seconds. Then modify your script to find them after
2.0 seconds.

2. Write a script that defines the variables

V

0

= 10

,

a

= 2

.

5

, and

z

= 4

1
3

, and then

evaluates the expression

V

=

V

0

1

z

a

2

+

z

2

.

Then find

V

for

z

= 8

2
3

and print it out (see

Note about printing

). Then find

V

for

z

= 13

by changing the value of

z

in your script.

3. Write a single Python script that calculates the following expressions:

(a)

2 +

e

2

.

8

13

2

(b)

1

(1 + ln 2)

3

.

5

1 +

5

(c)

sin

2

2

2 +

2

!

After running your script in the IPython shell, typing

a

,

b

, or

c

at the IPython

prompt should yield the value of the expressions in (a), (b), or (c), respectively.

4. A quadratic equation with the general form

ax

2

+

bx

+

c

= 0

has two solutions given by the quadratic formula

x

=

b

±

b

2

4

ac

2

a

.

2.12. Exercises

27


background image

Introduction to Python for Science, Release 0.9.23

(a) Given

a

,

b

, and

c

as inputs, write a script that gives the numerical values of

the two solutions. Write the constants

a

,

b

, and

c

as floats, and show that your

script gives the correct solutions for a few test cases when the solutions are real
numbers, that is, when the discriminant

b

2

4

ac

0

. Use the

print

function

in your script, discussed at the end of Section 2.8.1

Scripting Example 1

to

print out your two solutions.

(b) Written this way, however, your script gives an error message when the solu-

tions are complex. For example, see what happens when

a

= 1

,

b

= 2

, and

c

= 3

. You can fix this using statements in your script like

a = a+0j

after

setting

a

to some float value. Thus, you can make the script work for any set

of real inputs for

a

,

b

, and

c

. Again, use the

print

function to print out your

two solutions.

28

Chapter 2. Launching Python


background image

CHAPTER

THREE

STRINGS, LISTS, ARRAYS,

AND DICTIONARIES

The most import data structure for scientific computing in Python is the

NumPy array

.

NumPy arrays are used to store lists of numerical data and to represent vectors, matrices,
and even tensors. NumPy arrays are designed to handle large data sets efficiently and
with a minimum of fuss. The NumPy library has a large set of routines for creating,
manipulating, and transforming NumPy arrays. NumPy functions, like

sqrt

and

sin

,

are designed specifically to work with NumPy arrays. Core Python has an array data
structure, but it’s not nearly as versatile, efficient, or useful as the NumPy array. We will
not be using Python arrays at all. Therefore, whenever we refer to an “array,” we mean a
“NumPy array.”

Lists

are another data structure, similar to NumPy arrays, but unlike NumPy arrays, lists

are a part of core Python. Lists have a variety of uses. They are useful, for example,
in various bookkeeping tasks that arise in computer programming. Like arrays, they are
sometimes used to store data. However, lists do not have the specialized properties and
tools that make arrays so powerful for scientific computing. So in general, we prefer
arrays to lists for working with scientific data. For other tasks, lists work just fine and can
even be preferable to arrays.

Strings

are lists of keyboard characters as well as other characters not on your keyboard.

They are not particularly interesting in scientific computing, but they are nevertheless
necessary and useful. Texts on programming with Python typically devote a good deal of
time and space to learning about strings and how to manipulate them. Our uses of them
are rather modest, however, so we take a minimalist’s approach and only introduce a few
of their features.

Dictionaries

are like lists, but the elements of dictionaries are accessed in a different

29