0% found this document useful (0 votes)
7 views28 pages

Python Programming for Economics

Lecture Notes of an Introduction to Python

Uploaded by

Ivo Magalhães
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

Python Programming for Economics

Lecture Notes of an Introduction to Python

Uploaded by

Ivo Magalhães
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming

J.A. Matos, P.B. Vasconcelos

Numerical Methods for Economics


Master in Economics (FEP)

Contents
1 Introduction 3
1.1 Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Computer programming . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Programming languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Main concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Classification of programming languages . . . . . . . . . . . . . . . . . . . . . 7

2 Python 8
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.1 The Pythonic way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.2 Python identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.3 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3.2 Built-in types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3.3 Data structure example . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Control flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4.1 Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4.2 Advanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 Builtin functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.6 Standard library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3 Code organization 20
3.1 Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Contents 2

3.2.1 Purpose of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20


3.2.2 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3 Modules/packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.4 Good practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Scientific computing packages 24


4.1 Ecosystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.2 Base packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.3 Numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.4 Scipy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

5 Exercises 28

Numerical Methods for Economics Master in Economics


1 Introduction 3

1 Introduction
1.1 Concepts
1.1.1 Algorithms

Algorithms: What are they?


Definition
In mathematics and computer science, an algorithm is a finite sequence of mathematically rig-
orous instructions, typically used to solve a class of specific problems or to perform a compu-
tation. Algorithms are used as specifications for performing calculations and data processing.
More advanced algorithms can use conditionals to divert the code execution through various
routes (referred to as automated decision-making) and deduce valid inferences (referred to as
automated reasoning).
Source: [Link]

Algorithms: How are they shown?


Representations
Algorithms can be expressed in many kinds of notation, including natural languages, pseu-
docode, flowcharts, drakon-charts, programming languages or control tables (processed by
interpreters). Natural language expressions of algorithms tend to be verbose and ambiguous
and are rarely used for complex or technical algorithms. Pseudocode, flowcharts, drakon-
charts, and control tables are structured expressions of algorithms that avoid common ambi-
guities of natural language.
Source: [Link]

1.1.2 Computer programming

What it is?
Computer programming
or coding is the composition of sequences of instructions, called programs, that computers
can follow to perform tasks. It involves designing and implementing algorithms, step-by-step
specifications of procedures, by writing code in one or more programming languages.
Source: [Link]

Algorithms + Data Structures = Programs


Algorithms + Data Structures = Programs
is a 1976 book written by Niklaus Wirth covering some of the fundamental topics of system
engineering, computer programming, particularly that algorithms and data structures are in-
herently related. For example, if one has a sorted list one will use a search algorithm optimal
for sorted lists.

Numerical Methods for Economics Master in Economics


1 Introduction 4

The book is one of the most influential computer science books of its time and, like Wirth’s
other work, has been used extensively in education.
Source: [Link]

What is programming
Programming corresponds to the task of creating code:
• That means to put in code a given algorithm with the purpose to solve the problems we
are interested.

• That implies to organize the code in appropriate chunks/blocks. Those blocks, usually
correspond to functions and modules/packages.

• We also control the program flow, that means that the same code can take different paths
depending on its input.

1.2 Programming languages


1.2.1 Definition

What are they?


A programming language
is a system of notation for writing computer programs. Programming languages are described
in terms of their syntax (form) and semantics (meaning), usually defined by a formal language.
Languages usually provide features such as a type system, variables, and mechanisms for er-
ror handling. An implementation of a programming language is required in order to execute
programs, namely an interpreter or a compiler. An interpreter directly executes the source
code, while a compiler produces an executable program.
Source: [Link]

What are they used for?


Example
The best to way to explore modelling and simulation is though the use of a computer language
that provides us with the flexibility required to simulate and analyze the results.
In this case they allow easily to automate tasks that would be too time consuming otherwise.

1.2.2 Main concepts

Programming languages
The basic concepts
of a computer language are:

Numerical Methods for Economics Master in Economics


1 Introduction 5

• its structure;
• the data types;
• the libraries.

Or, in a more general sense,


a programming language is the results of its:
• structure;
• algorithms;
• data types.

Language structure
• syntax and grammar (that corresponds to the form);
• semantics (the meaning);
• control flow;
• code organization (functions, modules/packages/libraries).

Data types
How the different types of data are represented in the languages:
• numbers;
• text;
• tables;
• lists;
• etc.

Libraries
Refer to how other information can be found:
• contain data types and/or functions (algorithms);
• usually deal with a specific task;
• are organized as packages or modules (organizational difference only);
Classification:
• standard library (builtin/are guaranteed to be there);
• external ecosystem.

Numerical Methods for Economics Master in Economics


1 Introduction 6

1.3 Examples
Example of programming languages
There are lots of computer languages. In the scope of this course some of the most widely
used are:

• Python;

• R;

• Julia;

• Matlab/Octave.

In this course we will focus our study on the Python programming language.

R
R is, just as Python, a computer language widely used in Data Analysis but in also in other
more general areas like Computational Economics or Computational Finance.
Just like Python it has a very rich, diverse and capable ecosystem of packages. The language’s
origin are in the Data Analysis. Examples of packages used to hold, and then explore data are:

• DataFrame;

• [Link];

• other tidyverse package.

Due to the time constraints in this course we present a brief introduction to R in one of the
notebooks.

Julia

Julia is a high-level, general-purpose dynamic programming language. Its features


are well suited for numerical analysis and computational science.

From the Wikipedia page on Julia.

• For more information consult Julia website;

• You can also the Help context menu in Jupyter.

Due to the time constraints in this course we present a brief introduction to Julia in one of the
notebooks.

Numerical Methods for Economics Master in Economics


1 Introduction 7

1.4 Classification of programming languages


Programming language classification
Sometimes also referred as programming language paradigms or styles. Programming lan-
guages are often placed into four main categories:

imperative are designed to implement an algorithm in a specified order;

functional work by successively applying functions to the given parameters;

logic are designed so that the software, rather than the programmer, decides what order in
which the instructions are executed;

object oriented have as the main characteristics: data abstraction, inheritance, and dynamic
dispatch.

The same language can fall into several of these categories with varying degrees of support for
each of them. So, for example, both Python, R and Julia (the original trio that gave the name
to Jupyter) support imperative, functional and object oriented styles.

Numerical Methods for Economics Master in Economics


2 Python 8

2 Python
2.1 Introduction
Python programming language

Python is a high-level, general-purpose programming language. Its design philos-


ophy emphasizes code readability with the use of significant indentation via the
off-side rule.
Python is dynamically typed and garbage-collected. It supports multiple program-
ming paradigms, including structured (particularly procedural), object-oriented
and functional programming. It is often described as a "batteries included" lan-
guage due to its comprehensive standard library.

[Link]

History

• The first version was released in 1989 (!)

• Version 1.0 was released in 1993

• Version 2.0 was released in 2000


– The last branch was 2.7 (released on 4 July 2010)
– It was maintained until 1st January 2020

• Version 3.0 was released in December of 2008


– The current stable version is 3.13 (released on October 2024)

2.2 Syntax
2.2.1 The Pythonic way

Python philosophy

• Indentation serves to delimit code blocks;

• Python is meant to be an easily readable language.

• The number of functions that is always available, when a program starts (built-in), is
quite small. This is a design choice, all the other functions and data types that come
with Python are available in packages or modules.

[Link]

Numerical Methods for Economics Master in Economics


2 Python 9

Python philosophy
When we speak a human language there is a natural way to tell things, the idiomatic ex-
pressions. The same happens for Python, that is called the Pythonic way.
Python’s motto
is “Make simple things simple and complex things possible”.
There are several principles that are the core of python language like this.

• Try import this in your shell and see what the result is.

2.2.2 Python identifiers

Identifiers
Python identifiers correspond to names.
Examples of identifiers are:

• keywords:
for example def or return;

• variables;

• function names;

• module names:
for example import pandas as pd - pandas and pd are identifiers.

Example (function)

def colatz(n):
"this implements the function from the Colatz conjecture"

if n % 2 == 0: # n is even
return n//2 # // corresponds to the integer division
else: # n is odd
return 3*n+1

Identifiers on the example function


We have in the function above the following identifiers:

variables: n;

function names: colatz;

keywords: def; if; else; return.

Numerical Methods for Economics Master in Economics


2 Python 10

This function shows several elements of the Python syntax:


• In this case we are defining a function that given a number determines another based
on the Collatz conjecture [Link]
• This function takes one argument as input, named n;
• There is a documentation string at the begin that can be used to ask for help about the
purpose of function;
• Depending on the evenness of the input argument it returns:
– the integer division by two if the input is even;
– the input times 3 plus 1 if it is not (if n is odd).
• Everything that appears after, and including, the #(hash mark) is considered as human
comment and disregarded by the interpreter;
• We call to the lines below the function header the function body;
• The function body is defined through the indentation of the code.

2.2.3 Keywords

Reserved keywords

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

There are 3 other contextual keywords: match, case and _.

Operators
Note that some of the keywords are actual operators:
• and
• in
• is
• not
• or.

Numerical Methods for Economics Master in Economics


2 Python 11

Values
In the keywords we have also values (those are easy to identify since they are the only ones
capitalized):

• False

• True

• None

2.2.4 Operators

Examples

arithmetic: +, -, *, / ("true division"), // (floor division), % (modulus), and ** (exponentia-


tion);

assignment: = , :=, +=; -=; *=; /=, …

comparison: ==, !=, <, >, <=, >=, is, is not, in and not in;

logical: and and or.

2.3 Data types


2.3.1 Definition

Definition
Data types
In computer science and computer programming, a data type (or simply type) is (all at once):

• a collection or grouping of data values, usually specified by a set of possible values,

• with a set of allowed operations on these values (algorithms),

• and/or with a representation of these values as machine types.

[Link]

Data structures
A particular case of data types are:
Data structures
Some (data) types are very useful for storing and retrieving data and are called data structures.
One of the important features is the ease and efficiency that the data can be accessed and
updated.
[Link]

Numerical Methods for Economics Master in Economics


2 Python 12

Examples of data structures ontologies


Containers
We can think of them as containers that contain other data types. Those data types can be
them also data structures.
For example, a table is a data structure, the table is composed by columns that are them-
selves data structures.

Sequences
A data structure is a sequence if we can browse its content in a sequential way. For example
lists, strings, tuples and tables are examples of sequences.

We are interested in these data structures to work with real world data. In the next couple
of modules we will introduce and deal with them.
Some of the more important data structures that are interested are:

• arrays (numerical or others);

• lists;

• records (tuples);

• tables.

2.3.2 Built-in types

Hierarchy of the standard data types

Numerical Methods for Economics Master in Economics


2 Python 13

Source: [Link]
The purpose of this chart is just to show that there are relations between the standard types.

• The standard data types are builtin, that is they come directly with the installed Python,
and can be used immediately.

Numerical Methods for Economics Master in Economics


2 Python 14

The standard data types include:

• Numbers;

• Data Structures: Sequences, Set types and Mappings;

• Callable: functions, methods, classes;

• Modules.

2.3.3 Data structure example

The standard data types are not enough


Although the standard data types provide all the basic functionality for Python they are not
enough when dealing with real world problems.
For more specific tasks we need to resort to other data types:

• in the Python standard library (provides an extensive list of specialized data types);

• in external libraries (like the Scientific Python ecosystem that provide valuable data
types to work on practical problems).

Data types

datetime provides a data type to work with times and dates;

numpy provides numerical arrays (vectors, matrices, tensors);

pandas provides tables and data panels.

Example of a table of the students enrolled in a course

ID Name Birthday Height Erasmus


16 Joe 2000-02-04 1.80 F
15 Ana 1999-07-14 1.72 T
19 Tim 2000-10-05 1.75 T
14 Eva 1999-10-12 1.82 F

• int - integer numbers;

• list - lists;

• str - text strings;

• tuple - tuples.

Numerical Methods for Economics Master in Economics


2 Python 15

Columns have homogeneous datatypes:

ID: Integer numbers/int


E.g. any element of {16, 15, 19, 14}

Name: strings (text)/str


E.g. any element of {“Joe”, “Ana”, “Tim”, “Eva”}

Birthday: dates/[Link]
E.g. [Link](1999,10,12)

Height: real number/float


E.g. any element of {1.80, 1.72, 1.75, 1.82}

Erasmus: Boolean/bool
There are only two possible values: {F, T }

It is possible to use datatypes that act as containers to other:


Dictionary: Pair (key, value)/dict
E.g. {16: 1.80, 15: 1.72, 19: 1.75, 14: 1.82}

Tuple: (Row/Record) Container with objects of different types/tuple


E.g. (19, “Tim”, datetime(2000,10,5), 1.75, T)

List: (Column) Container with objects of the same type/list


E.g. [F, T, T, F]

Numerical array: (Column)/[Link]


E.g. [Link]([1.80, 1.72, 1.75, 1.82])

DataFrame: full table/[Link]

2.4 Control flow


2.4.1 Basic

Control flow
Definition
In computer science, control flow (or flow of control) is the order in which individual state-
ments, instructions or function calls of an imperative program are executed or evaluated.
[Link]

Numerical Methods for Economics Master in Economics


2 Python 16

Choice: Loops:

If-then(-else) statements; Count-controlled repeat a given number of times;

Case and switch statements. Condition-controlled repeat while some condition


holds;

Collection-controlled repeat for all elements of a collec-


tion.

Examples

# Condition-controlled
n, prod = 1, 1
while prod < 1e100:
n += 1 # augmented assignment, the same as: n = n + 1
prod *= n # the same as above but now for multiplication

print(n, prod)

# Count/collection-controlled
prod = 1
for i in range(1, n+1):
prod *= i

print(prod)

For more examples see [Link]


[Link]#top.

2.4.2 Advanced

Advanced
Non-local control flow:

• exceptions;

• generators;

• asynchronous I/O.

Exception example

def inverse(n):
return 1/n

def half_inverse(n):
w = inverse(n)

Numerical Methods for Economics Master in Economics


2 Python 17

print("inverse concluded")
return 2*w

def try_dvision(n):
try:
z = half_inverse(n)
except ZeroDivisionError:
print ("Can not divide by zero")

2.5 Builtin functions


The basic functions
Just like Python has standard data types there are also functions builtin that can be used
directly.
Besides the list of keywords there are other identifiers that we can use in our Python pro-
grams. Almost all those identifiers correspond to builtin functions.
The list of functions available by default for Python is very small. Most other languages have
a lot more functions available at start.
Python 3 has 71 built-in functions, as it can be seen in the Python documentation https:
//[Link]/3/library/[Link].

Data types
Of those functions that are builtins some are related with the standard data types that we
saw already:
• bool - for boolean values; • int - integer numbers;

• bytes - for text without encoding; • list - lists;

• complex - complex numbers; • str - text strings;

• dict - dictionaries; • tuple - tuples.

• float - real numbers;


There are a few other, more specialized, data types that do not interest us for the moment.

Generic functions
From the built-in functions, that do not correspond to data types, others are generic func-
tions that operate on some or all of the data types defined above:

• abs - absolute value (useful for numbers);

• all and any - useful for boolean containers;

• len - length, number of elements, of a container;

• max and min - maximum and minimum of a container (lists or tuples);

Numerical Methods for Economics Master in Economics


2 Python 18

• pow - evaluates a power, similar to the ** operator;

• print - print function;

• range - returns a range;

• round - to round numbers;

• sum - sum all the elements of a list like container;

• type - give us the data type of a given object.

2.6 Standard library


Standard library

Rather than building all of its functionality into its core, Python was designed to be
highly extensible via modules. This compact modularity has made it particularly
popular as a means of adding programmable interfaces to existing applications.
Van Rossum’s vision of a small core language with a large standard library and
easily extensible interpreter stemmed from his frustrations with ABC, which es-
poused the opposite approach.

[Link]
The components from the standard library can be accessed using the import statement, just
like any external packages. The only difference regarding external packages is that if Python
is properly installed we can be sure that those packages are always available.
In Python the standard library is quite extensive.

Documentation
All the documentation regarding the Python standard library can be found in its site:

• Brief Tour of the Standard Library [Link]

• Brief Tour of the Standard Library — Part II [Link]


[Link]

• The Python Standard Library [Link]

Examples
Types of packages in the standard library (there are more):

Numerical Methods for Economics Master in Economics


2 Python 19

• Text Processing Services • File Formats

• Binary Data Services • Generic Operating System Services

• Data Types • Networking and Interprocess Communica-


tion
• Numeric and Mathematical Modules
• Internet Data Handling
• Functional Programming Modules
• Structured Markup Processing Tools
• File and Directory Access
• Software Packaging and Distribution
• Data Persistence
• Python Runtime Services
• Data Compression and Archiving
• Importing Modules

Numerical Methods for Economics Master in Economics


3 Code organization 20

3 Code organization
3.1 Code
What is a program?
• A piece of code that does a given task;
• Where is it (in the case of Python/R/Julia)?
– in the code cells of a Jupyter notebook;
– in an external file, that in the particular case of these languages is called a script.

3.2 Functions
3.2.1 Purpose of functions

What is the best way to organize the code? (1: functions)


If the same code is used over and over again the best way is to organize that code in func-
tions, as the basic blocks:
• Each function should have a well defined task to do, and should do it well;
• It should have a well defined identification of input arguments/parameters;
• It should clearly define what is its output, and how many arguments are return, if pos-
sible with very few, or none, side-effects;
• It should be well documented.
For more details see [Link]
html.

Example
def format_name(first_name, last_name, middle_name=None):
"""
Formats a full name with optional middle name.

Args:
first_name: The first name.
last_name: The last name.
middle_name: (Optional) The middle name.

Returns:
The formatted full name.
"""

if middle_name:
return f"{first_name} {middle_name} {last_name}"
else:
return f"{first_name} {last_name}"

Numerical Methods for Economics Master in Economics


3 Code organization 21

Advantages of writing the code with functions


Some of the advantages of creating functions, instead of just writing code without any struc-
ture, are:

• Functions accept input arguments and return output arguments (clearly define its role);

• User defined functions act like built-in functions;

• Functions allow to document the code and have it available immediately;

• Internal variables are local to the function (no pollution of the workspace);

• Avoids to type the same commands over and over again;

• The idea (implemented through the algorithm) is written in a single place;

• Functions allow code reuse (future use or to share code);

• Functions allow for better testing since the code is a single place, and the test can be
thoroughly applied.

3.2.2 Parameters

Classification
The way we pass and receive argument is flexible and simple.
We can classify the different types of arguments based on:

Presence if they need to be there or not;

Pass mode on how they are passed to the function.

Presence: optional or mandatory?


Default arguments
are a kind of syntactic sugar where, if no argument is passed, the argument retains its default
value.
In particular that makes these arguments optional since if we do not pass them they still get
the right value.

Warning
Its use is pervasive on all the functions of the standard library as well as external libraries that
we use.

Numerical Methods for Economics Master in Economics


3 Code organization 22

Passing modes
There are, basically, two ways to pass arguments to functions:
Position the argument is determined based on the order it is passed (first, second, ...);
Keyword the argument has a name that refers explicitly to the name of that argument.

Note
Positional arguments always come first while keyword arguments always come last.
For readability and performance, it makes sense to restrict the way arguments can be passed
so that a user needs only to look at the function definition to determine if items are passed by
position, by position or keyword, or by just by keyword.
Further documentation:
• [Link]
• [Link]
• [Link]

3.3 Modules/packages
What is the best way to organize the code? (2: modules)
Modules
• If a function is used in many different places it should be placed into a module;
• In Python that means an external file where the code is placed and from where it can
be used by importing it;
• A regular module is thus enclosed within a file.

What is the best way to organize the code? (3: packages)


Packages/libraries
• A package is a module that is implemented using a folder/directory structure and that
can have other modules/packages inside;
• A library is a broader term that refers to a collection of reusable code functionalities.
In Python, libraries are usually implemented as packages (or a collection of packages).
They provide tools to perform specific tasks or solve problems in a particular domain
(like data science, web development, machine learning, etc.).

So even although technically packages and libraries refer to different concepts, they are so
closely related that is usual to use both terms interchangeably.
Not only that but the Python type for both modules and packages is just module.
A simple rule
is then that we install libraries and import packages and modules.

Numerical Methods for Economics Master in Economics


3 Code organization 23

3.4 Good practices


Examples of good practices with code
What follows is a set of good practices that gets reflected in the final results:

• store the code such that it is organized and if possible place it in functions;

• comment the code appropriately;

• even if a data type can be expanded at will always define its dimension in advance;

• make your code able to work with scalar and vectors from the beginning;

• global variables should be avoided;

• always prefer functions to scripts for intermediate calculations;

• be consistent, be it in the name of variables or in the indentation styles.

Numerical Methods for Economics Master in Economics


4 Scientific computing packages 24

4 Scientific computing packages


4.1 Ecosystem
Scientific Python ecosystem

The Unexpected Effectiveness of Python in Science (Jake VanderPlas)


[Link]

4.2 Base packages


Scientific Python packages (basis)
In this course we will look into some of the base packages of Scientific Computing using
Python:

• numpy defines multidimensional arrays that are suitable for high performance calcula-
tions while at the same time providing a nice interface;

• Scipy extends the features provided by numpy for numerical analysis;

• matplotlib provides the features required to produce high quality graphics. Since it
uses numpy objects internally it is a natural match to work with the previous packages;

• pandas provides features to work with tables that are not all necessarily numeric. Pro-
vides a nice interface to easily work, transform and display tabular data. It is built on
top of/uses numpy and matplotlib.

All these packages are the building blocks used by more specific packages that are built on top
of them.

Numerical Methods for Economics Master in Economics


4 Scientific computing packages 25

4.3 Numpy
numpy
Numpy sets the basis for working with large quantities of numbers in Python.
The purpose of this is also in the simplicity and efficiency of operations:
• Its functions are universal, i.e. they apply element by element:
Example: [Link]([Link]([1,2,3])) -> [Link]([exp(1),exp(2),exp(3)])

• Numerical arrays support broadcasting, i.e. where possible they expand automatically
to make operations possible:
Example: 1 + [Link]([1,2,3]) -> [Link]([2,3,4])

numpy modules
In order to avoid having everything in the main module there are several modules for spe-
cific tasks. Some that we will be using are:
• [Link] for the most common and efficient linear algebra operations (for vector,
matrices, tensors).

• [Link] module implements pseudo-random number generators (PRNGs or RNGs,


for short) with the ability to draw samples from a variety of probability distributions.

4.4 Scipy
scipy
scipy complements Numpy with operations that are useful for scientific computing/computa-
tional economics operations. It is package that has in one place several modules/sub-packages
that are useful in simulation:
[Link] for numerical integration of functions and of differential equations;

[Link] for numerical optimization (finding minimum and maximum) or finding ze-
ros of functions;

[Link] extends the linear algebra operations of numpy;

[Link] for statistical related functions and methods.

Random number generators (pseudo-random)


We can use the number generators both from Numpy or, for even more probability distribu-
tions, from Scipy.
The way to do it is to call rng = [Link].default_rng() and then call the different meth-
ods from the random number generator:
[Link] generates random numbers on [0, 1[ following an uniform distribution;

Numerical Methods for Economics Master in Economics


4 Scientific computing packages 26

[Link] generates random numbers following a standard normal distribution (mean and
standard deviation are parameters);

[Link], [Link], [Link] for, respectively, the exponential, Poisson and


Gamma distributions;

[Link] generates integer numbers in a given range.

For a more complete list of supported distributions consult both Numpy and Scipy documen-
tation.

4.5 Conclusion
Mastery implies practice: practical motivation analogy

1. Yarn knot (ABoK #2688)

2. Manrope knot (ABoK #847)

3. Granny knot (ABoK #1206)

Numerical Methods for Economics Master in Economics


4 Scientific computing packages 27

4. Wall and crown knot (ABoK #670, #671)

5. Matthew Walker’s knot (ABoK #681)

6. Shroud knot (ABoK #1580)

7. Turk’s head knot (ABoK #1278-#1397)

8. Overhand knot, Figure-of-eight knot (ABoK #514, #520)

9. Reef knot, Square knot (ABoK #1402)

10. Two half-hitches (ABoK #54)

It is knot a problem
Knots can be either decorative or practical. In practice:

• Knot tying skills are often transmitted by sailors, scouts, climbers, canyoners, cavers,
arborists, rescue professionals, stagehands, fishermen, linemen and surgeons.

• It is important to know the strengths an weaknesses of each knot in order to apply it


well/adequately.

• It is necessary to practice or else we forget it.

Taking some artistic freedom we could say that data types are the statistics and programming
knots. And so all the previous considerations about knots apply with the corresponding equiv-
alencies.

Numerical Methods for Economics Master in Economics


5 Exercises 28

5 Exercises
Python functions

1. Write a function that returns the sum of two real values.


Does your code works if the input arguments are vectors or matrices?

2. Write a function that evaluates the mean of the values of a vector by using the available
function sum.
How do the results compare with the statistical function [Link]? Does this code works
with matrices?

3. Write a function that evaluates the mean, median and standard deviation from the val-
ues of a vector.

Python control flow

1. Suppose that you intend successively to divide π by 2. What is the largest term in this
succession that is smaller or equal to 0.01?
What is the smaller ratio that is larger than 0.01?

2. Create a function that generates an Hilbert matrix of order m ∗ n. The Hilbert matrix is
H = [hij ] , i = 1..m, j = 1..n such that

1
hij = .
i+j−1

a) using for cycles;


b) ** not using for cycles.
Tip: The last part can be done using numerical arrays

Numerical Methods for Economics Master in Economics

You might also like