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

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

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

Добавлен: 17.04.2021

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

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

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

Introduction to Python for Science, Release 0.9.23

Out[66]:

array([[

-

1.

,

2.

,

3.

],

[ 7., 5., 2.]])

Functions also act on an element-to-element basis

In [67]:

sin(b)

Out[67]:

array([[

0.84147098

,

-

0.7568025

,

-

0.95892427

],

[ 0.41211849, 0.6569866 , -0.7568025 ]])

Multiplying two arrays together is done on an element-by-element basis. Using the ma-
trices

b

and

c

defined above, multiplying them together gives

In [68]:

b

Out[68]:

array([[

1.

,

4.

,

5.

],

[ 9., 7., 4.]])

In [69]:

c

Out[69]:

array([[

0

,

1

,

2

],

[3, 4, 5]])

In [70]:

b

*

c

Out[70]:

array([[

0.

,

4.

,

10.

],

[ 27., 28., 20.]])

Of course, this requires that both arrays have the same shape. Beware: array multipli-
cation, done on an element-by-element basis, is not the same as matrix multiplication
as defined in linear algebra. Therefore, we distinguish between

array

multiplication and

matrix

multiplication in Python.

Normal matrix multiplication is done with NumPy’s

dot

function. For example, defining

d

to be the transpose of

c

using using the

array

function’s

T

transpose method creates

an array with the correct dimensions that we can use to find the matrix product of

b

and

d

:

In [71]:

d

=

c

.

T

In [72]:

d

Out[72]:

array([[

0

,

3

],

[1, 4],

[2, 5]])

In [73]:

dot(b,d)

Out[73]:

array([[

14.

,

44.

],

[ 15., 75.]])

3.3. NumPy arrays

45


background image

Introduction to Python for Science, Release 0.9.23

3.3.5 Differences between lists and arrays

While lists and arrays are superficially similar—they are both multi-element data
structures—they behave quite differently in a number of circumstances. First of all, lists
are part of the core Python programming language; arrays are a part of the numerical
computing package NumPy. Therefore, you have access to NumPy arrays only if you
load the NumPy package using the

import

command.

Here we list some of the differences between Python lists and NumPy arrays, and why
you might prefer to use one or the other depending on the circumstance.

The elements of a NumPy array must all be of the same type

, whereas the ele-

ments of a Python list can be of completely different types.

NumPy arrays support “vectorized” operations

like element-by-element addi-

tion and multiplication. This is made possible, in part, by the fact that all elements
of the array have the same type, which allows array operations like element-by-
element addition and multiplication to be carried out by very efficient C loops. Such
“vectorized” operations on arrays, which includes operations by NumPy functions
such as

numpy.sin

and

numpy.exp

, are much faster than operations performed

by loops using the core Python

math

package functions, such as

math.sin

and

math.exp

, that act only on individual elements and not on whole lists or arrays.

Adding one or more additional elements to a NumPy array creates a new array
and destroys the old one.

Therefore it can be very inefficient to build up large

arrays by appending elements one by one, especially if the array is very large,
because you repeatedly create and destroy large arrays. By contrast, elements can
be added to a list without creating a whole new list. If you need to build an array
element by element, it is usually better to build it as a list, and then convert it
to an array when the list is complete. At this point, it may be difficult for you
to appreciate how and under what circumstances you might want build up an array
element by element. Examples are provided later on: for an example see the section
on

Looping over arrays in user-defined functions

.

3.4 Dictionaries

A Python

list

is a collection of Python objects indexed by an ordered sequence of integers

starting from zero. A

dictionary

is also collection of Python objects, just like a list,

but one that is indexed by strings or numbers (not necessarily integers and not in any
particular order) or even tuples! For example, suppose we want to make a dictionary of
room numbers indexed by the name of the person who occupies each room. We create
our dictionary using curly brackets

{...}

.

46

Chapter 3. Strings, Lists, Arrays, and Dictionaries


background image

Introduction to Python for Science, Release 0.9.23

In [1]:

room

=

{

"Emma"

:

309

,

"Jacob"

:

582

,

"Olivia"

:

764

}

The dictionary above has three entries separated by commas, each entry consisting of a

key

, which in this case is a string, and a

value

, which in this case is a room number. Each

key and its value are separated by a colon. The syntax for accessing the various entries is
similar to a that of a list, with the key replacing the index number. For example, to find
out the room number of Olivia, we type

In [2]:

room[

"Olivia"

]

Out[2]:

764

The key need not be a string; it can be any immutable Python object. So a key can be a
string, an integer, or even a tuple, but it can’t be a list. And the elements accessed by their
keys need not be a string, but can be almost any legitimate Python object, just as for lists.
Here is a weird example

In [3]:

weird

=

{

"tank"

:

52

,

846

:

"horse"

,

"bones"

:[

23

,

...:

"fox"

,

"grass"

],

"phrase"

:

"I am here"

}

In [4]:

weird[

"tank"

]

Out[4]:

52

In [5]:

weird[

846

]

Out[5]:

’horse’

In [6]:

weird[

"bones"

]

Out[6]:

[

23

,

’fox’

,

’grass’

]

In [7]:

weird[

"phrase"

]

Out[7]:

’I am here’

Dictionaries can be built up and added to in a straightforward manner

In [8]:

d

=

{}

In [9]:

d[

"last name"

]

=

"Alberts"

In [10]:

d[

"first name"

]

=

"Marie"

In [11]:

d[

"birthday"

]

=

"January 27"

In [12]:

d

Out[12]:

{

’birthday’

:

’January 27’

,

’first name’

:

’Marie’

,

’last name’: ’Alberts’}

3.4. Dictionaries

47


background image

Introduction to Python for Science, Release 0.9.23

You can get a list of all the keys or values of a dictionary by typing the dictionary name
followed by

.keys()

or

.values()

.

In [13]:

d

.

keys()

Out[13]:

[

’last name’

,

’first name’

,

’birthday’

]

In [14]:

d

.

values()

Out[14]:

[

’Alberts’

,

’Marie’

,

’January 27’

]

In other languages, data types similar to Python dictionaries may be called “hashmaps”
or “associative arrays”, so you may see such term used if you read on the web about
dictionaries.

3.5 Random numbers

Random numbers are widely used in science and engineering computations. They can
be used to simulate noisy data, or to model physical phenomena like the distribution of
velocities of molecules in a gas, or to act like the roll of dice in a game. There are even
methods for numerically evaluating multi-dimensional integrals using random numbers.

The basic idea of a random number generator is that it should be able to produce a
sequence of numbers that are distributed according to some predetermined distribution
function. NumPy provides a number of such random number generators in its library

numpy.random

. Here we focus on three:

rand

,

randn

, and

randint

.

3.5.1 Uniformly distributed random numbers

The

rand(num)

function creates and array of

num

floats uniformly distributed on the

interval from 0 to 1.

In [1]:

rand()

Out[1]:

0.5885170150833566

In [2]:

rand(

5

)

Out[2]:

array([

0.85586399

,

0.21183612

,

0.80235691

,

0.65943861, 0.25519987])

If

rand

has no argument, a single random number is generated. Otherwise, the argument

specifies the number of size of the array of random numbers that is created.

If you want random numbers uniformly distributed over some other interval, say from

a

to

b

, then you can do that simply by stretching the interval so that it has a width of

b

a

48

Chapter 3. Strings, Lists, Arrays, and Dictionaries


background image

Introduction to Python for Science, Release 0.9.23

and displacing the lower limit from 0 to

a

. The following statements produce random

numbers uniformly distributed from 10 to 20:

In [3]:

a, b

=

10

,

20

In [4]:

(b

-

a)

*

rand(

20

)

+

a

Out[4]:

array([

10.99031149

,

18.11685555

,

11.48302458

,

18.25559651, 17.55568817, 11.86290145,

17.84258224, 12.1309852 , 14.30479884,

12.05787676, 19.63135536, 16.58552886,

19.15872073, 17.59104303, 11.48499468,

10.16094915, 13.95534353, 18.21502143,

19.61360422, 19.21058726])

3.5.2 Normally distributed random numbers

The function

randn(num)

produces a

normal

or

Gaussian

distribution of

num

random

numbers with a mean of 0 and a standard deviation of 1. That is, they are distributed
according to

P

(

x

) =

1

2

π

e

1
2

x

2

.

The figure below shows histograms for the distributions of 10,000 random numbers gen-
erated by the

np.random.rand

(blue) and

np.random.randn

(green) functions.

As advertised, the

np.random.rand

function produces an array of random numbers

that is uniformly distributed between the values of 0 and 1, while

np.random.randn

function produces an array of random numbers that follows a distribution of mean 0 and
standard deviation 1.

If we want a random numbers with a Gaussian distribution of width

σ

centered about

x

0

,

we stretch the interval by a factor of

σ

and displace it by

x

0

. The following code produces

20 random numbers normally distributed around 15 with a width of 10:

In [5]:

x0, sigma

=

15

,

10

In [6]:

sigma

*

randn(

20

)

+

x0

Out[6]:

array([

9.36069244

,

13.49260733

,

6.12550102

,

18.50471781,

9.89499319, 14.09576728,

12.45076637, 17.83073628,

2.95085564,

18.2756275 , 14.781659

, 31.80264078,

20.8457924 , 13.87890601, 25.41433678,

15.44237582, 21.2385386 , -3.91668973,

31.19120157, 26.24254326])

3.5. Random numbers

49