Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Applying Math with Python
Applying Math with Python

Applying Math with Python: Over 70 practical recipes for solving real-world computational math problems , Second Edition

eBook
Can$44.99 Can$50.99
Paperback
Can$63.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Applying Math with Python

Mathematical Plotting with Matplotlib

Plotting is a fundamental tool in all of mathematics. A good plot can reveal hidden details, suggest future directions, verify results, or reinforce an argument. It is no surprise, then, that the scientific Python stack features a powerful and flexible plotting library called Matplotlib.

In this chapter, we will plot functions and data in a variety of styles and create figures that are fully labeled and annotated. We will create three-dimensional plots, customize the appearance of figures, create figures that contain multiple plots using subplots, and save figures directly to files for applications that are not running in an interactive environment.

Plotting is one of the most important aspects covered in this book. Plotting data, functions, or solutions can often help you gain an understanding of a problem that can really help to reason about your methods. We will see plotting again in every chapter of this book.

In this chapter, we will cover the following recipes:

  • Basic plotting with Matplotlib
  • Adding subplots
  • Plotting with error bars
  • Saving Matplotlib figures
  • Surface and contour plots
  • Customizing three-dimensional plots
  • Plotting vector fields with quiver plots

Technical requirements

The main plotting package for Python is Matplotlib, which can be installed using your favorite package manager, such as pip:

python3.10 -m pip install matplotlib

This will install the most recent version of Matplotlib, which, at the time of writing this book, is version 3.5.2.

Matplotlib contains numerous sub-packages, but the main user interface (UI) is the matplotlib.pyplot package, which, by convention, is imported under the plt alias. This is achieved using the following import statement:

import matplotlib.pyplot as plt

Many of the recipes in this chapter also require NumPy, which, as usual, is imported under the np alias.

The code for this chapter can be found in the Chapter 02 folder of the GitHub repository at https://github.com/PacktPublishing/Applying-Math-with-Python-2nd-Edition/tree/main/Chapter%2002.

Basic plotting with Matplotlib

Plotting is an important part of understanding behavior. So much can be learned by simply plotting a function or data that would otherwise be hidden. In this recipe, we will walk through how to plot simple functions or data using Matplotlib, set the plotting style, and add labels to a plot.

Matplotlib is a very powerful plotting library, which means it can be rather intimidating to perform simple tasks with it. For users who are used to working with MATLAB and other mathematical software packages, there is a state-based interface called pyplot. There is also an object-oriented interface (OOI), which might be more appropriate for more complex plots. In either case, the pyplot interface is a convenient way to create basic objects.

Getting ready

Most commonly, the data that you wish to plot will be stored in two separate NumPy arrays, which we will label x and y for clarity (although this naming does not matter in practice). We will demonstrate plotting the graph of a function, so we will generate an array of x values and use the function to generate the corresponding y values. We’re going to plot three different functions over the range on the same axes:

def f(x):
  return x*(x - 2)*np.exp(3 – x)
def g(x):
  return x**2
def h(x):
  return 1 - x

Let’s plot these three functions in Python using Matplotlib.

How to do it...

Before we can plot the function, we must generate x and y data to be plotted. If you are plotting existing data, you can skip these commands. We need to create a set of x values that cover the desired range, and then use the function to create y values:

  1. The linspace routine from NumPy is ideal for creating arrays of numbers for plotting. By default, it will create 50 equally spaced points between the specified arguments. The number of points can be customized by providing an additional argument, but 50 is sufficient for most cases:
    x = np.linspace(-0.5, 3.0)  # 50 values between -0.5 and 3.0
  2. Once we have created x values, we can generate y values:
    y1 = f(x)  # evaluate f on the x points
    y2 = g(x)  # evaluate g on the x points
    y3 = h(x)  # evaluate h on the x points
  3. To plot the data, we first need to create a new figure and attach axes objects, which can be achieved by calling the plt.subplots routine without any arguments:
    fig, ax = plt.subplots()

Now, we use the plot method on the ax object to plot the first function. The first two arguments are and coordinates to be plotted, and the third (optional) argument specifies that the line color should be black:

ax.plot(x, y1, "k")  # black solid line style

To help distinguish the plots for the other functions, we plot those with a dashed line and a dot-dash line:

ax.plot(x, y2, "k--")  # black dashed line style
ax.plot(x, y3, "k.-")  # black dot-dashed line style

Every plot should have a title and axis labels. In this case, there isn’t anything interesting to label the axes with, so we just label them "x" and "y":

ax.set_title("Plot of the functions f, g, and h")
ax.set_xlabel("x")
ax.set_ylabel("y")

Let’s also add a legend to help you distinguish between the different function plots without having to look elsewhere to see which line is which:

ax.legend(["f", "g", "h"])

Finally, let’s annotate the plot to mark the intersection between the functions and with text:

ax.text(0.4, 2.0, "Intersection")

This will plot the y values against the x values on a new figure. If you are working within IPython or with a Jupyter notebook, then the plot should automatically appear at this point; otherwise, you might need to call the plt.show function to make the plot appear:

plt.show()

If you use plt.show, the figure should appear in a new window. We won’t add this command to any further recipes in this chapter, but you should be aware that you will need to use it if you are not working in an environment where plots will be rendered automatically, such as an IPython console or a Jupyter Notebook. The resulting plot should look something like the plot in Figure 2.1:

Figure 2.1 – Three functions on a single set of axes, each with a different style, with labels, legend, and an annotation

Figure 2.1 – Three functions on a single set of axes, each with a different style, with labels, legend, and an annotation

Note

If you are using a Jupyter notebook and the subplots command, you must include the call to subplots within the same cell as the plotting commands or the figure will not be produced.

How it works…

Here, we’re using the OOI because it allows us to keep track of exactly which figure and axes object we’re plotting on. This isn’t so important here where we have only a single figure and axes, but one can easily envisage situations where you might have two or more figures and axes concurrently. Another reason to follow this pattern is to be consistent when you add multiple subplots—see the Adding subplots recipe.

You can produce the same plot as in the recipe via the state-based interface by using the following sequence of commands:

plt.plot(x, y1, "k", x, y2, "k--", x, y3, "k.-")
plt.title("Plot of the functions f, g, and h")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(["f", "g", "h"])
plt.text(0.4, 2.0, "Intersection")

If there are currently no Figure or Axes objects, the plt.plot routine creates a new Figure object, adds a new Axes object to the figure, and populates this Axes object with the plotted data. A list of handles to the plotted lines is returned. Each of these handles is a Lines2D object. In this case, this list will contain a single Lines2D object. We could use this Lines2D object to further customize the appearance of the line later.

Notice that in the preceding code, we combined all the calls to the plot routine together. This is also possible if you use the OOI; the state-based interface is passing the arguments to the axes method on the set of axes that it either retrieves or creates.

The object layer of Matplotlib interacts with a lower-level backend, which does the heavy lifting of producing the graphical plot. The plt.show function issues an instruction to the backend to render the current figure. There are a number of backends that can be used with Matplotlib, which can be customized by setting the MPLBACKEND environment variable, modifying the matplotlibrc file, or by calling matplotlib.use from within Python with the name of an alternative backend. By default, Matplotlib picks a backend that is appropriate for the platform (Windows, macOS, Linux) and purpose (interactive or non-interactive), based on which backends are available. For example, on the author’s system, the QtAgg backend is the default. This is an interactive backend based on the Anti-Grain Geometry (AGG) library. Alternatively, one might want to use the QtCairo backend, which uses the Cairo library for rendering.

Note

The plt.show function does more than simply call the show method on a figure. It also hooks into an event loop to correctly display the figure. The plt.show routine should be used to display a figure, rather than the show method on a Figure object.

The format string used to quickly specify the line style has three optional parts, each consisting of one or more characters. The first part controls the marker style, which is the symbol that is printed at each data point; the second controls the style of the line that connects the data points; the third controls the color of the plot. In this recipe, we only specified the line style. However, one could specify both line style and marker style or just marker style. If you only provide the marker style, no connecting lines are drawn between the points. This is useful for plotting discrete data where no interpolation between points is necessary.

Four line-style parameters are available: a solid line (-), a dashed line (--), a dash-dot line (-.), or a dotted line (:). Only a limited number of colors can be specified in the format string; they are red, green, blue, cyan, yellow, magenta, black, and white. The character used in the format string is the first letter of each color (with the exception of black), so the corresponding characters are r, g, b, c, y, m, k, and w, respectively.

In the recipe, we saw three examples of these format strings: the single k format string only changed the color of the line and kept the other settings at default (small point markers and unbroken blue line); the k-- and k.- format strings both changed the color and the line style. For an example of changing the point style, see the There’s more... section and Figure 2.2:

Figure 2.2 - Plot of three sets of data, each plotted using a different marker style

Figure 2.2 - Plot of three sets of data, each plotted using a different marker style

The set_title, set_xlabel, and set_ylabel methods simply add the text argument to the corresponding position of the Axes object. The legend method, as called in the preceding code, adds the labels to the datasets in the order that they were added to the plot—in this case, y1, y2, and then y3.

There are a number of keyword arguments that can be supplied to the set_title, set_xlabel, and set_ylabel routines to control the style of the text. For example, the fontsize keyword can be used to specify the size of the label font in the usual pt point measure.

The annotate method on the Axes object adds arbitrary text to a specific position on the plot. This routine takes two arguments—the text to display as a string and the coordinates of the point at which the annotation should be placed. This routine also accepts keyword arguments that can be used to customize the style of the annotation.

There’s more…

The plt.plot routine accepts a variable number of positional inputs. In the preceding code, we supplied two positional arguments that were interpreted as x values and y values (in that order). If we had instead provided only a single array, the plot routine would have plotted the values against their position in the array; that is, the x values are taken to be 0, 1, 2, and so on.

The plot method also accepts a number of keyword arguments that can also be used to control the style of a plot. Keyword arguments take precedence over format string parameters if both are present, and they apply to all sets of data plotted by the call. The keyword to control the marker style is marker, the keyword for the line style is linestyle, and the keyword for color is color. The color keyword argument accepts a number of different formats to specify a color, which includes RGB values as a (r, g, b) tuple, where each character is a float between 0 and 1 or is a hex string. The width of the line plotted can be controlled using the linewidth keyword, which should be provided with a float value. Many other keyword arguments can be passed to plot; a list is given in the Matplotlib documentation. Many of these keyword arguments have a shorter version, such as c for color and lw for linewidth.

In the this recipe, we plotted a large number of coordinates generated by evaluating functions on a selection of values. In other applications, one might have data sampled from the real world (as opposed to generated). In these situations, it might be better to leave out the connecting lines and simply plot the markers at the points. Here is an example of how this might be done:

y1 = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y2 = np.array([1.2, 1.6, 3.1, 4.2, 4.8])
y3 = np.array([3.2, 1.1, 2.0, 4.9, 2.5])
fig, ax = plt.subplots()
ax.plot(y1, 'o', y2, 'x', y3, '*', color="k")

The result of these commands is shown in Figure 2.2. Matplotlib has a specialized method for producing scatter plots such as this, called scatter.

Other aspects of the plot can be customized by using methods on the Axes object. The axes ticks can be modified using the set_xticks and set_yticks methods on the Axes object, and the grid appearance can be configured using the grid method. There are also convenient methods in the pyplot interface that apply these modifications to the current axes (if they exist).

For example, we modify the axis limits, set the ticks at every multiple of 0.5 in both the and direction, and add a grid to the plot by using the following commands:

ax.axis([-0.5, 5.5, 0, 5.5]) # set axes
ax.set_xticks([0.5*i for i in range(9)])  # set xticks
ax.set_yticks([0.5*i for i in range(11)]) # set yticks
ax.grid()  # add a grid

Notice how we set the limits slightly larger than the extent of the plot. This is to avoid markers being placed on the boundary of the plot window.

Matplotlib has many other plotting routines besides the plot routine described here. For example, there are plotting methods that use a different scale for the axes, including the logarithmic or axes separately (semilogx or semilogy, respectively) or together (loglog). These are explained in the Matplotlib documentation. The scatter plotting routine may be useful if you wish to plot discrete data on axes without connecting the points with a line. This allows more control over the style of the marker. For example, you can scale the marker according to some additional information.

We can use a different font by using the fontfamily keyword, the value of which can be the name of a font or serif, sans-serif, or monospace, which will choose the appropriate built-in font. A complete list of modifiers can be found in the Matplotlib documentation for the matplotlib.text.Text class.

Text arguments can also be rendered using TeX for additional formatting by supplying usetex=True to the routine. We’ll demonstrate the use of TeX formatting of labels in Figure 2.3 in the following recipe. This is especially useful if the title or axis label contains a mathematical formula. Unfortunately, the usetex keyword argument cannot be used if TeX is not installed on the system—it will cause an error in this case. However, it is still possible to use the TeX syntax for formatting mathematical text within labels, but this will be typeset by Matplotlib, rather than by TeX.

Adding subplots

Occasionally, it is useful to place multiple related plots within the same figure side by side but not on the same axes. Subplots allow us to produce a grid of individual plots within a single figure. In this recipe, we will see how to create two plots side by side on a single figure using subplots.

Getting ready

You will need the data to be plotted on each subplot. As an example, we will plot the first five iterates of Newton’s method applied to the function with an initial value of on the first subplot, and for the second, we will plot the error of the iterate. We first define a generator function to get the iterates:

def generate_newton_iters(x0, number):
  iterates = [x0]
  errors = [abs(x0 - 1.)]
  for _ in range(number):
       x0 = x0 - (x0*x0 - 1.)/(2*x0)
       iterates.append(x0)
       errors.append(abs(x0 - 1.))
    return iterates, errors

This routine generates two lists. The first list contains iterates of Newton’s method applied to the function, and the second contains the error in the approximation:

iterates, errors = generate_newton_iters(2.0, 5)

How to do it...

The following steps show how to create a figure that contains multiple subplots:

  1. We use the subplots routine to create a new figure and references to all of the Axes objects in each subplot, arranged in a grid with one row and two columns. We also set the tight_layout keyword argument to True to fix the layout of the resulting plots. This isn’t strictly necessary, but it is in this case as it produces a better result than the default:
    fig, (ax1, ax2) = plt.subplots(1, 2, 
    tight_layout=True) 
    #1 row, 2 columns
  2. Once Figure and Axes objects are created, we can populate the figure by calling the relevant plotting method on each Axes object. For the first plot (displayed on the left), we use the plot method on the ax1 object, which has the same signature as the standard plt.plot routine. We can then call the set_title, set_xlabel, and set_ylabel methods on ax1 to set the title and the x and y labels. We also use TeX formatting for the axes labels by providing the usetex keyword argument; you can ignore this if you don’t have TeX installed on your system:
    ax1.plot(iterates, "kx")
    ax1.set_title("Iterates")
    ax1.set_xlabel("$i$", usetex=True)
    ax1.set_ylabel("$x_i$", usetex=True)
  3. Now, we can plot the error values on the second plot (displayed on the right) using the ax2 object. We use an alternative plotting method that uses a logarithmic scale on the axis, called semilogy. The signature for this method is the same as the standard plot method. Again, we set the axes labels and the title. Again, the use of usetex can be left out if you don’t have TeX installed:
    ax2.semilogy(errors, "kx") # plot y on logarithmic scale
    ax2.set_title("Error")
    ax2.set_xlabel("$i$", usetex=True)
    ax2.set_ylabel("Error")

The result of this sequence of commands is shown here:

Figure 2.3 - Multiple subplots on the same Matplotlib figure

Figure 2.3 - Multiple subplots on the same Matplotlib figure

The left-hand side plots the first five iterates of Newton’s method, and the right-hand side is the approximation error plotted on a logarithmic scale.

How it works...

A Figure object in Matplotlib is simply a container for plot elements, such as Axes, of a certain size. A Figure object will usually only hold a single Axes object, which occupies the entire figure area, but it can contain any number of Axes objects in the same area. The subplots routine does several things. It first creates a new figure and then creates a grid with the specified shape in the figure area. Then, a new Axes object is added to each position of the grid. The new Figure object and one or more Axes objects are then returned to the user. If a single subplot is requested (one row and one column, with no arguments) then a plain Axes object is returned. If a single row or column is requested (with more than one column or row, respectively), then a list of Axes objects is returned. If more than one row and column are requested, a list of lists, with rows represented by inner lists filled with Axes objects, will be returned. We can then use the plotting methods on each of the Axes objects to populate the figure with the desired plots.

In this recipe, we used the standard plot method for the left-hand side plot, as we have seen in previous recipes. However, for the right-hand side plot, we used a plot where the axis had been changed to a logarithmic scale. This means that each unit on the axis represents a change of a power of 10 rather than a change of one unit so that 0 represents , 1 represents 10, 2 represents 100, and so on. The axes labels are automatically changed to reflect this change in scale. This type of scaling is useful when the values change by an order of magnitude, such as the error in an approximation, as we use more and more iterations. We can also plot with a logarithmic scale for only by using the semilogx method, or both axes on a logarithmic scale by using the loglog method.

There’s more...

There are several ways to create subplots in Matplotlib. If you have already created a Figure object, then subplots can be added using the add_subplot method of the Figure object. Alternatively, you can use the subplot routine from matplotlib.pyplot to add subplots to the current figure. If one does not yet exist, it will be created when this routine is called. The subplot routine is a convenience wrapper of the add_subplot method on the Figure object.

In the preceding example, we created two plots with differently scaled axes. This demonstrates one of the many possible uses of subplots. Another common use is for plotting data in a matrix where columns have a common x label and rows have a common y label, which is especially common in multivariate statistics when investigating the correlation between various sets of data. The plt.subplots routine for creating subplots accepts the sharex and sharey keyword parameters, which allows the axes to be shared among all subplots or among a row or column. This setting affects the scale and ticks of the axes.

See also

Matplotlib supports more advanced layouts by providing the gridspec_kw keyword arguments to the subplots routine. See the documentation for matplotlib.gridspec for more information.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Compute complex mathematical problems using programming logic with the help of step-by-step recipes
  • Learn how to use Python libraries for computation, mathematical modeling, and statistics
  • Discover simple yet effective techniques for solving mathematical equations and apply them in real-world statistics

Description

The updated edition of Applying Math with Python will help you solve complex problems in a wide variety of mathematical fields in simple and efficient ways. Old recipes have been revised for new libraries and several recipes have been added to demonstrate new tools such as JAX. You'll start by refreshing your knowledge of several core mathematical fields and learn about packages covered in Python's scientific stack, including NumPy, SciPy, and Matplotlib. As you progress, you'll gradually get to grips with more advanced topics of calculus, probability, and networks (graph theory). Once you’ve developed a solid base in these topics, you’ll have the confidence to set out on math adventures with Python as you explore Python's applications in data science and statistics, forecasting, geometry, and optimization. The final chapters will take you through a collection of miscellaneous problems, including working with specific data formats and accelerating code. By the end of this book, you'll have an arsenal of practical coding solutions that can be used and modified to solve a wide range of practical problems in computational mathematics and data science.

Who is this book for?

Whether you are a professional programmer or a student looking to solve mathematical problems computationally using Python, this is the book for you. Advanced mathematics proficiency is not a prerequisite, but basic knowledge of mathematics will help you to get the most out of this Python math book. Familiarity with the concepts of data structures in Python is assumed.

What you will learn

  • Become familiar with basic Python packages, tools, and libraries for solving mathematical problems
  • Explore real-world applications of mathematics to reduce a problem in optimization
  • Understand the core concepts of applied mathematics and their application in computer science
  • Find out how to choose the most suitable package, tool, or technique to solve a problem
  • Implement basic mathematical plotting, change plot styles, and add labels to plots using Matplotlib
  • Get to grips with probability theory with the Bayesian inference and Markov Chain Monte Carlo (MCMC) methods
Estimated delivery fee Deliver to Canada

Economy delivery 10 - 13 business days

Can$24.95

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 09, 2022
Length: 376 pages
Edition : 2nd
Language : English
ISBN-13 : 9781804618370
Category :
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Canada

Economy delivery 10 - 13 business days

Can$24.95

Product Details

Publication date : Dec 09, 2022
Length: 376 pages
Edition : 2nd
Language : English
ISBN-13 : 9781804618370
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 203.97
Practical Discrete Mathematics
Can$83.99
Applying Math with Python
Can$63.99
Hands-On Mathematics for Deep Learning
Can$55.99
Total Can$ 203.97 Stars icon

Table of Contents

12 Chapters
Chapter 1: An Introduction to Basic Packages, Functions, and Concepts Chevron down icon Chevron up icon
Chapter 2: Mathematical Plotting with Matplotlib Chevron down icon Chevron up icon
Chapter 3: Calculus and Differential Equations Chevron down icon Chevron up icon
Chapter 4: Working with Randomness and Probability Chevron down icon Chevron up icon
Chapter 5: Working with Trees and Networks Chevron down icon Chevron up icon
Chapter 6: Working with Data and Statistics Chevron down icon Chevron up icon
Chapter 7: Using Regression and Forecasting Chevron down icon Chevron up icon
Chapter 8: Geometric Problems Chevron down icon Chevron up icon
Chapter 9: Finding Optimal Solutions Chevron down icon Chevron up icon
Chapter 10: Improving Your Productivity Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

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

Filter reviews by




Yiqiao Yin Jan 28, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really enjoy reading this. The book reboot my knowledge in several core mathematical fields. It provides a whole package in mathematics, numpy, scipy, and matplotlib. As I progress in learning the materials, I gradually understand the topics in the book with regards to calculus, probability, and network and so on. It's a highly engineering and physics-based title. The chapters took me through a collection of miscellaneous problems with data formats and coding walkthrough. I highly recommend it!
Amazon Verified review Amazon
Akul Apr 19, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really liked reading this title. The book helped me review my knowledge in complex as well as foundational mathematical topics with its application in Python. I’ll recommend this book for people wanting to get a refresher on mathematical concepts applicable in Machine Learning/Data Science which in turn will help improve their conceptual understanding of the model’s black box. A must read indeed!!
Amazon Verified review Amazon
H2N Nov 16, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an indispensable guide for Python enthusiasts tackling mathematical challenges. It begins with foundational Python packages, including NumPy and SciPy, then advances to Matplotlib for essential plotting skills. The chapters progress through calculus, differential equations, and randomness and probability basics, providing a solid mathematical base. It explores practical Python applications in areas such as trees, networks, and data analysis, and includes regression, forecasting, and geometric problem-solving. Additionally, it introduces optimization and game theory, and concludes with valuable productivity tips for Python in mathematical problem-solving, making it a comprehensive resource for varied mathematical pursuits with Python.
Amazon Verified review Amazon
Dror Feb 11, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Python has become the programming language of choice for computation in most science and engineering disciplines, including math, physics, data science and many others. This is largely due to its vast ecosystem of mathematical and scientific packages, but this large ecosystem can also be overwhelming for many students and beginners.This highly practical book provides a gentle introduction to using Python for solving problems in math and science. It begins with a clear and useful overview of the fundamental Python packages for scientific computing, such as NumPy, SciPy and Matplotlib. It then progresses to describe how to solve a diverse collection of problems in math and science using Python, in areas such as data analysis and statistics, networks, regression and forecasting, optimization, and game theory. These descriptions are clear and concise, and gradually present additional common and helpful Python packages for scientific programming.I would highly recommend this book to anyone interested in learning how to use Python for scientific computing and data analysis. It requires no more than basic knowledge of the Python programming language, and will be ideal for students in math, science and engineering who are taking their first steps in the world of scientific programming. Experienced software engineers and other Python programmers looking to expand their knowledge into scientific computing and data analysis will also highly benefit from reading this wonderful and rather unique book.
Amazon Verified review Amazon
Steven Fernandes Mar 09, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The updated Applying Math with Python edition offers efficient solutions for complex problems in various mathematical fields. It includes revised old recipes and new ones to showcase tools such as JAX. You'll refresh core mathematical concepts and learn about packages in Python's scientific stack. Gradually, you'll tackle advanced topics like calculus, probability, and networks, leading to exploring Python's applications in data science, statistics, forecasting, geometry, and optimization. The book concludes with miscellaneous problems, including data formats and code acceleration. You'll gain practical coding solutions to solve various computational math and data science problems.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

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