Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Scientific Computing with Python 3
Scientific Computing with Python 3

Scientific Computing with Python 3: An example-rich, comprehensive guide for all of your Python computational needs

By Claus Führer , Jan Erik Solem , Olivier Verdier
€41.99
Book Dec 2016 332 pages 1st Edition
eBook
€32.99 €22.99
Print
€41.99
Subscription
€14.99 Monthly
eBook
€32.99 €22.99
Print
€41.99
Subscription
€14.99 Monthly

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Dec 23, 2016
Length 332 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786463517
Category :
Concepts :

Estimated delivery fee Deliver to France

Premium 7 - 10 business days

€23.95
(Includes tracking information)
Table of content icon View table of contents Preview book icon Preview Book

Scientific Computing with Python 3

Chapter 1. Getting Started

In this chapter, we will give a brief overview of the principal syntactical elements of Python. Readers who have just started learning programming are guided through the book in this chapter. Every topic is presented here in a how-to way and will be explained later in the book in a deeper conceptual manner and will also be enriched with many applications and extensions.

Readers who are already familiar with another programming language will come across, in this chapter, the Python way of doing classical language constructs. It offers them a quick start to Python programming.

Both types of readers are encouraged to take this chapter as a brief guideline when zigzagging through the book. However, before we start we have to make sure that everything is in place and you have the correct version of Python installed together with the main modules for Scientific Computing and tools, such as a good editor and a shell, which helps in code developing and testing.

Read the following section, even if you already have access to a computer with Python installed. You might want to adjust things to have a working environment conforming to the presentation in this book.

Installation and configuration instructions


Before diving into the subject of the book you should have all the relevant tools installed on your computer. We will give you some advice and recommend tools that you might want to use. We only describe public domain and free tools.

Installation

There are currently two major versions of Python; the 2.x branch and the new 3.x branch. There are language incompatibilities between these branches and one has to be aware of which one to use. This book is based on the 3.x branch, considering the language up to release 3.5.

For this book you need to install the following:

  • The interpreter: Python 3.5 (or later)
  • The modules for scientific computing: SciPy with NumPy
  • The module for graphical representation of mathematical results: matplotlib
  • The shell: IPython
  • A Python related editor: Spyder (refer to the following Figure 1.1, Spyder), Geany

The installation of these is eased by the so-called distribution packages. We recommend that you use Anaconda. The default screen of Spyder consists of an editor window on left, a console window in the lower right corner which gives access to an IPython shell and a help window in the upper right corner as shown in the following figure:

Figure 1.1: The default screen of Spyder consists of an editor window on left, a console window in the lower right corner which gives access to an IPython shell and a help window in the upper right corner.

Anaconda

Even if you have Python pre-installed on your computer, we recommend that you create your personal Python environment that allows you to work without the risk of accidentally affecting the software on which your computer's functionality might depend. With a virtual environment, such as Anaconda, you are free to change language versions and install packages without the unintended side-effects.

If the worst happens and you screw things up totally, just delete the Anaconda directory and start again. Running the Anaconda installer will install Python, a Python development environment and editor (Spyder), the shell IPython, and the most important packages for numerical computations, for example SciPy, NumPy, and matplotlib.

You can install additional packages with conda install within your virtual environment created by Anaconda (refer for official documentation from[2]).

Configuration

Most Python codes will be collected in files. We recommend that you use the following header in all your Python files:

from scipy import *
from matplotlib.pyplot import *

With this, you make sure that all standard modules and functions used in this book, such as SciPy, are imported. Without this step, most of the examples in the book would raise errors. Many editors, such as Spyder, provide the possibility to create a template for your files. Look for this feature and put the preceding header into a template.

Python Shell

The Python shell is good but not optimal for interactive scripting. We therefore recommend using IPython instead (refer to [26] for the official documentation). IPython can be started in different ways:

  • In a terminal shell by running the following command:ipython
  • By directly clicking on an icon called Jupyter QT Console

  • When working with Spyder you should use an IPython console (refer to Figure 1.1, Spyder).

Executing scripts

You often want to execute the contents of a file. Depending on the location of the file on your computer, it is necessary to navigate to the correct location before executing the contents of a file.

  • Use the command cd in IPython in order to move to the directory where your file is located.
  • To execute the contents of a file named myfile.py, just run the following command in the IPython shell
      run myfile

Getting Help

Here are some tips on how to use IPython:

  • To get help on an object, just type ? after the object's name and then return.
  • Use the arrow keys to reuse the last executed commands.
  • You may use the Tab key for completion (that is, you write the first letter of a variable or method and IPython shows you a menu with all the possible completions).
  • Use Ctrl+D to quit.
  • Use IPython's magic functions. You can find a list and explanations by applying  %magic  on the command prompt.

Tip

You can find out more about IPython in its online documentation, [15].

Jupyter – Python notebook

The Jupyter notebook is a fantastic tool for demonstrating your work. Students might want to use it to make and document homework and exercises and teachers can prepare lectures with it, even slides and web pages.

If you have installed Python via Anaconda, you already have everything for Jupyter in place. You can invoke the notebook by running the following command in the terminal window:

jupyter notebook

A browser window will open and you can interact with Python through your web browser.

Program and program flow


A program is a sequence of statements that are executed in a top-down order. This linear execution order has some important exceptions:

  • There might be a conditional execution of alternative groups of statements (blocks), which we refer to as branching.
  • There are blocks that are executed repetitively, which is called looping (refer to the following Figure 1.2, Program flow).
  • There are function calls that are references to another piece of code, which is executed before the main program flow is resumed. A function call breaks the linear execution and pauses the execution of a program unit while it passes the control to another unit-a function. When this gets completed, its control is returned to the calling unit.

Figure 1.2: Program flow

Python uses a special syntax to mark blocks of statements: a keyword, a colon, and an indented sequence of statements, which belong to the block (refer to the following Figure 1.3 Block command).

Figure 1.3: Block command

Comments

If a line in a program contains the symbol #, everything following on the same line is considered as a comment:

# This is a comment of the following statement
a = 3  # ... which might get a further comment here  

Line joining

A backslash \ at the end of the line marks the next line as a continuation line, that is, explicit line joining. If the line ends before all the parentheses are closed, the following line will automatically be recognized as a continuation line, that is, implicit line joining.

Basic types


Let's go over the basic data types that you will encounter in Python.

Numbers

A number may be an integer, a real number, or a complex number. The usual operations are:

  • addition and subtraction, + and -
  • multiplication and division, * and /
  • power, **

Here is an example:

2 ** (2 + 2) # 16
1j ** 2 # -1
1. + 3.0j

Note

The symbol for complex numbers

j  is a symbol to denote the imaginary part of a complex number. It is a syntactic element and should not be confused with multiplication by a variable. More on complex numbers can be found in section Numeric Types of Chapter 2, Variables and Basic Types.

Strings

Strings are sequences of characters, enclosed by simple or double quotes:

'valid string'
"string with double quotes"
"you shouldn't forget comments"
'these are double quotes: ".." '

You can also use triple quotes for strings that have multiple lines:

"""This is
 a long,
 long string"""

Variables

A variable is a reference to an object. An object may have several references. One uses the assignment operator = to assign a value to a variable:

x = [3, 4] # a list object is created
y = x # this object now has two labels: x and y
del x # we delete one of the labels
del y # both labels are removed: the object is deleted

The value of a variable can be displayed by the print function:

x = [3, 4] # a list object is created
print(x)

Lists

Lists are a very useful construction and one of the basic types in Python. A Python list is an ordered list of objects enclosed by square brackets. One can access the elements of a list using zero-based indexes inside square brackets:

L1 = [5, 6]
L1[0] # 5
L1[1] # 6
L1[2] # raises IndexError
L2 = ['a', 1, [3, 4]]
L2[0] # 'a'
L2[2][0] # 3
L2[-1] # last element: [3,4]
L2[-2] # second to last: 1

Indexing of the elements starts at zero. One can put objects of any type inside a list, even other lists. Some basic list functions are as follows:

  • list(range(n))} creates a list with n elements, starting with zero:
      print(list(range(5))) # returns [0, 1, 2, 3, 4]
  • len gives the length of a list:
      len(['a', 1, 2, 34]) # returns 4
  • append is used to append an element to a list:
      L = ['a', 'b', 'c']
      L[-1] # 'c'
      L.append('d')
      L # L is now ['a', 'b', 'c', 'd']
      L[-1] # 'd'

Operations on lists

  • The operator + concatenates two lists:

          L1 = [1, 2]
          L2 = [3, 4]
          L = L1 + L2 # [1, 2, 3, 4]
  • As one might expect, multiplying a list with an integer concatenates the list with itself several times:

    n*L is equivalent to making n additions.

          L = [1, 2]
          3 * L # [1, 2, 1, 2, 1, 2]

Boolean expressions

A Boolean expression is an expression that may have the value True or False. Some common operators that yield conditional expressions are as follow:

  •  Equal, ==
  •  Not equal, !=
  •  Less than, Less than or equal to, < , <=
  •  Greater than, Greater than or equal to, > , >=

One combines different Boolean values with or and and. The keyword not , gives the logical negation of the expression that follows. Comparisons can be chained so that, for example, x < y < z is equivalent to x < y and y < z. The difference is that y is only evaluated once in the first example. In both cases, z is not evaluated at all when the first condition, x < y, evaluates to False:

2 >= 4  # False
2 < 3 < 4 # True
2 < 3 and 3 < 2 # False
2 != 3 < 4 or False # True
2 <= 2 and 2 >= 2 # True
not 2 == 3 # True
not False or True and False # True!

Note

Precedence rules

The <, >, <=, >=, !=, and == operators have higher precedence than not.  The operators and, or have the lowest precedence. Operators with higher precedence rules are evaluated before those with lower.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Your ultimate resource for getting up and running with Python numerical computations
  • Explore numerical computing and mathematical libraries using Python 3.x code with SciPy and NumPy modules
  • A hands-on guide to implementing mathematics with Python, with complete coverage of all the key concepts

Description

Python can be used for more than just general-purpose programming. It is a free, open source language and environment that has tremendous potential for use within the domain of scientific computing. This book presents Python in tight connection with mathematical applications and demonstrates how to use various concepts in Python for computing purposes, including examples with the latest version of Python 3. Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, polynomials, and much more.

What you will learn

[*] The principal syntactical elements of Python [*] The most important and basic types in Python [*] The essential building blocks of computational mathematics, linear algebra, and related Python objects [*] Plot in Python using matplotlib to create high quality figures and graphics to draw and visualize your results [*] Define and use functions and learn to treat them as objects [*] How and when to correctly apply object-oriented programming for scientific computing in Python [*] Handle exceptions, which are an important part of writing reliable and usable code [*] Two aspects of testing for scientific programming: Manual and Automatic

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Dec 23, 2016
Length 332 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786463517
Category :
Concepts :

Estimated delivery fee Deliver to France

Premium 7 - 10 business days

€23.95
(Includes tracking information)

Table of Contents

23 Chapters
Scientific Computing with Python 3 Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Authors Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Acknowledgement Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Getting Started Chevron down icon Chevron up icon
2. Variables and Basic Types Chevron down icon Chevron up icon
3. Container Types Chevron down icon Chevron up icon
4. Linear Algebra – Arrays Chevron down icon Chevron up icon
5. Advanced Array Concepts Chevron down icon Chevron up icon
6. Plotting Chevron down icon Chevron up icon
7. Functions Chevron down icon Chevron up icon
8. Classes Chevron down icon Chevron up icon
9. Iterating Chevron down icon Chevron up icon
10. Error Handling Chevron down icon Chevron up icon
11. Namespaces, Scopes, and Modules Chevron down icon Chevron up icon
12. Input and Output Chevron down icon Chevron up icon
13. Testing Chevron down icon Chevron up icon
14. Comprehensive Examples Chevron down icon Chevron up icon
15. Symbolic Computations - SymPy Chevron down icon Chevron up icon
References Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela