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

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

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

Добавлен: 17.04.2021

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

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

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

Introduction to Python for Science, Release 0.9.23

SciPy

provides a wide spectrum of mathematical functions and numerical

routines for Python. SciPy makes extensive use of NumPy arrays so
when you import SciPy, you should always import NumPy too. In
addition to providing basic mathematical functions, SciPy provides
Python “wrappers” for numerical software written in other languages,
like Fortran, C, or C++. A “wrapper” provides a transparent easy-to-
use Python interface to standard numerical software, such as routines
for doing curve fitting and numerically solving differential equations.
SciPy greatly extends the power of Python and saves you the trouble
of writing software in Python that someone else has already written
and optimized in some other language. You can find more information
about SciPy at

http://docs.scipy.org/doc/scipy/reference/

.

MatPlotLib

is the standard Python package for making two and three

dimensional plots.

MatPlotLib makes extensive use of NumPy

arrays.

You will make all of your plots in Python using this

package.

You can find more information about MatPlotLib at

http://MatPlotLib.sourceforge.net/

.

We will use these three modules extensively and therefore will provide introductions to
their capabilities as we develop Python in this manual. The links above provide much
more extensive information and you will certainly want to refer to them from time to
time.

These modules, NumPy, MatPlotLib, and SciPy, are built into the IPython shell so we
can use them freely in that environment. Later, when we introduce Python programs (or
scripts), we will see that in those cases you must explicitly load these modules using the

import

command to have access to them.

Finally, we note that you can write your own Python modules. They are a convenient way
of packaging and storing Python code so that you can reuse it. We defer learning about
how to write modules until after we have learned about Python.

2.6 Python functions: a first look

A function in Python is similar to a mathematical function. In consists of a name and and
one or more arguments contained inside parentheses, and it produces some output. For
example, the NumPy function

sin(x)

calculates the sine of the number

x

(where

x

is

expressed in radians). Let’s try it out in the IPython shell:

In [1]:

sin(

0.5

)

Out[1]:

0.47942553860420301

2.6. Python functions: a first look

15


background image

Introduction to Python for Science, Release 0.9.23

The argument of the function can be a number or any kind of expression whose output
produces a number. For example, the function

log(x)

calculates the nature logarithm.

All of the following expressions are legal and produce the expected output:

In [2]:

log(sin(

0.5

))

Out[2]:

-

0.73516668638531424

In [3]:

log(sin(

0.5

)

+

1.0

)

Out[3]:

0.39165386283471759

In [4]:

log(

5.5

/

1.2

)

Out[4]:

1.5224265354444708

2.6.1 Some NumPy functions

NumPy includes an extensive library of mathematical functions. In the table below,
we list some of the most useful ones.

A much more complete list is available at

http://docs.scipy.org/doc/numpy/reference/ufuncs.html#math-operations

.

Function

Description

sqrt(x)

Square root of

x

exp(x)

Exponential of x,

i.e.

e

x

log(x)

Natural log of x,

i.e.

ln

x

log10(x)

Base 10 log of

x

degrees(x)

Converts

x

from radians to degrees

radians(x)

Converts

x

from degrees to radians

sin(x)

Sine of

x

(

x

in radians)

cos(x)

Cosine

x

(

x

in radians)

tan(x)

Tangent

x

(

x

in radians)

arcsin(x)

Arc sine (in radians) of

x

arccos(x)

Arc cosine (in radians) of

x

arctan(x)

Arc tangent (in radians) of

x

fabs(x)

Absolute value of

x

round(x)

Rounds a float to nearest integer

floor(x)

Rounds a float

down

to nearest integer

ceil(x)

Rounds a float

up

to nearest integer

sign(x)

-1 if

x <

0

, +1 if

x >

0

, 0 if

x

= 0

The functions discussed here all have one input and one output. Python functions can,
in general, have multiple inputs and multiple outputs. We will discuss these and other
features of functions later when we take up functions in the context of user-defined func-
tions.

16

Chapter 2. Launching Python


background image

Introduction to Python for Science, Release 0.9.23

2.6.2 Keyword arguments

In addition to regular arguments, Python functions can have keyword arguments
(

kwargs

). Keyword arguments are

optional

arguments that need not be specified when

a function is called. See

Basic plotting

for examples of the use of keyword arguments.

For the moment, we don’t need them so we defer a full discussion of keyword arguments
until we introduce

user defined functions

.

2.7 Variables

2.7.1 Names and the assignment operator

A variable is a name that is used to store data. It can be used to store different kinds of
data, but here we consider the simplest case where the data is a single numerical value.
Here are a few examples:

In [1]:

a

=

23

In [2]:

p, q

=

83.4

, sqrt(

2

)

The equal sign “

=

” is the assignment operator. In the first statement, it assigns the value

of 23 to the variable

a

. In the second statement it assigns a value of 83.4 to

p

and a value

of 1.4142135623730951 to

q

. To be more precise, the name of a variable, such as

a

, is

associated with a

memory location

in your computer; the assignment variable tells the

computer to put a particular piece of data, in this case a numerical value, in that memory
location. Note that Python stores the

numerical value

, not the expression used to generate

it. Thus,

q

is assigned the 17-digit number 1.4142135623730951 generated by evaluating

the expression

sqrt(2)

,

not

with

2

. (Actually the value of

q

is stored as a binary,

base 2, number using scientific notation with a mantissa and an exponent.)

Suppose we write

In [3]:

b

=

a

In this case Python associates a new memory location with the name

b

, distinct from the

one associated with

a

, and sets the value stored at that memory location to 23, the value

of

a

. The following sequence of statements demonstrate that fact. Can you see how?

Notice that simply typing a variable name and pressing

Return

prints out the value of

the variable.

In [4]:

a

=

23

2.7. Variables

17


background image

Introduction to Python for Science, Release 0.9.23

In [5]:

b

=

a

In [6]:

a

Out[6]:

23

In [7]:

b

Out[7]:

23

In [8]:

a

=

12

In [9]:

a

Out[9]:

12

In [10]:

b

Out[10]:

23

The assignment variable works from right to left; that is, it assigns the value of the number
on the right to the variable name on the left. Therefore, the statement “

5=a

” makes no

sense in Python. The assignment operator “

=

” in Python is not equivalent to the equals

sign “

=

” we are accustomed to in algebra.

The assignment operator can be used to increment or change the value of a variable

In [11]:

b

=

b

+

1

In [12]:

b

Out[12]:

24

The statement,

b = b+1

makes no sense in algebra, but in Python (and most computer

languages), it makes perfect sense: it means “add 1 to the current value of

b

and assign

the result to

b

.” This construction appears so often in computer programming that there

is a special set of operators to perform such changes to a variable:

+=

,

-=

,

*=

, and

/=

.

Here are some examples of how they work:

In [13]:

c , d

=

4

,

7.92

In [14]:

c

+=

2

In [15]:

c

Out[15]:

6

In [16]:

c

*=

3

In [16]:

c

Out[16]:

18

18

Chapter 2. Launching Python


background image

Introduction to Python for Science, Release 0.9.23

In [17]:

d

/= -

2

In [17]:

d

Out[17]:

-

3.96

In [18]:

d

-=

4

In [19]:

d

Out[19]:

-

7.96

Verify that you understand how the above operations work.

2.7.2 Legal and recommended variable names

Variable names in Python must start with a letter, and can be followed by as many al-
phanumeric characters as you like. Spaces are not allowed in variable names. However,
the underscore character “

_

” is allowed, but no other character that is not a letter or a

number is permitted.

Recall that Python is

case sensitive

, so the variable

a

is distinct from the variable

A

.

We recommend giving your variables descriptive names as in the following calculation:

In [20]:

distance

=

34.

In [21]:

time_traveled

=

0.59

In [22]:

velocity

=

distance

/

time_traveled

In [23]:

velocity

Out[23]:

57.6271186440678

The variable names

distance

,

time_traveled

, and

velocity

immediately re-

mind you of what is being calculated here. This is good practice. But so is keeping
variable names reasonably short, so don’t go nuts!

2.7.3 Reserved words in Python

There are also some names or words that are reserved by Python for special purposes or
functions. You must avoid using these names, which are provided here for your reference:

2.7. Variables

19