John Paul Mueller - Algorithms For Dummies

Здесь есть возможность читать онлайн «John Paul Mueller - Algorithms For Dummies» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Algorithms For Dummies: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Algorithms For Dummies»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Your secret weapon to understanding—and using!—one of the most powerful influences in the world today
Algorithms For Dummies,
Algorithms For Dummies

Algorithms For Dummies — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Algorithms For Dummies», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Algorithms For Dummies - изображение 55You don’t have to type the source code for this chapter manually. In fact, using the downloadable source is a lot easier. You can find the source for this chapter in the \A4D2E\A4D2E; 04; Basic Vectors and Matrixes.ipynb, \A4D2E\A4D2E; 04; Binary Search.ipynb, and \A4D2E\A4D2E; 04; Recursion.ipynb files of the downloadable source. See the Introduction for details on how to find these source files.

Performing Calculations Using Vectors and Matrixes

To perform useful work with Python, you often need to work with larger amounts of data that come in specific forms. These forms have odd-sounding names, but the names are quite important. The three terms you need to know for this chapter are as follows:

Scalar: A single base data item. For example, the number 2 shown by itself is a scalar.

Vector: A one-dimensional array (essentially a list) of data items. For example, an array containing the numbers 2, 3, 4, and 5 would be a vector.

Matrix: A two-or-more-dimensional array (essentially a table) of data items. For example, an array containing the numbers 2, 3, 4, and 5 in the first row and 6, 7, 8, and 9 in the second row is a matrix.

Python provides an interesting assortment of features on its own, but you'd still need to do a lot of work to perform some tasks. To reduce the amount of work you do, you can rely on code written by other people and found in packages. The following sections describe how to use the NumPy package ( https://numpy.org/ ) to perform various tasks on scalars, vectors, and matrixes. This chapter provides an overview of NumPy by emphasizing the features you use later (see https://www.w3schools.com/python/numpy/default.asp for more details).

Understanding scalar and vector operations

The NumPy package provides essential functionality for scientific computing in Python. To use numpy, you import it using a command such as import numpy as np. Now you can access numpyusing the common two-letter abbreviation np.

Algorithms For Dummies - изображение 56Python provides access to just one data type in any particular category. For example, if you need to create a variable that represents a number without a decimal portion, you use the integer data type. Using a generic designation like this is useful because it simplifies code and gives the developer a lot less to worry about. However, in scientific calculations, you often need better control over how data appears in memory, which means having more data types, something that numpyprovides for you. For example, you might need to define a particular scalar as a short(a value that is 16 bits long). Using numpy, you could define it as myShort = np.short(15). The NumPy package provides access to an assortment of data types ( https://numpy.org/doc/stable/reference/arrays.scalars.html ).

Use the numpy array()function to create a vector. For example, myVect = np.array([1, 2, 3, 4])creates a vector with four elements. In this case, the vector contains standard Python integers. You can also use the arrange()function to produce vectors, such as myVect = np.arange(1, 10, 2), which fills myVectwith [1, 3, 5, 7, 9]. The first input tells the starting point, the second the stopping point, and the third the step between each number. A fourth argument lets you define the data type for the vector.

You can also create a vector with a specific data type. All you need to do is specify the data type like this: myVect = np.int16([1, 2, 3, 4])to fill myVectwith a vector containing 16-bit integer values. To verify this for yourself, you can use print(type(myVect[0])), which outputs .

Algorithms For Dummies - изображение 57You can perform basic math functions on vectors as a whole, which makes numpyincredibly useful and less prone to errors that can occur when using programming constructs such as loops to perform the same task. For example, when starting with myVect = np.array([1, 2, 3, 4]), myVect + 1produces an output of array([2, 3, 4, 5], dtype=int16). Note that the output tells you specifically which data type is in use. As you might expect, myVect - 1produces an output of array([0, 1, 2, 3], dtype=int16).

As a final thought on scalar and vector operations, you can also perform both logical and comparison tasks. For example, the following code performs comparison operations on two arrays:

a = np.array([1, 2, 3, 4])b = np.array([2, 2, 4, 4]) print(a == b)print(a < b)

The output in this case is:

[False True False True][ True False True False]

Starting with two vectors, aand b, the code checks whether the individual elements in aequal those in b. In this case, a[0]doesn't equal b[0]. However, a[1]does equal b[1]. The output is a vector of type boolthat contains Trueor Falsevalues based on the individual comparisons.

Logical operations rely on special functions. You check the logical output of the Boolean operators AND, OR, XOR, and NOT. Here is an example of the logical functions:

a = np.array([True, False, True, False])b = np.array([True, True, False, False]) print(np.logical_or(a, b))print(np.logical_and(a, b))print(np.logical_not(a))print(np.logical_xor(a, b))

When you run this code, you see these outputs:

[ True True True False][ True False False False][False True False True][False True True False]

You can read more about the logic functions at https://numpy.org/doc/stable/reference/routines.logic.html .

Performing vector multiplication

Adding, subtracting, or dividing vectors occurs on an element-by-element basis, as described in the previous section. However, when it comes to multiplication, things get a little odd. In fact, depending on what you really want to do, things can become quite odd indeed. Consider the sort of multiplication discussed in the previous section. Both myVect * myVectand np.multiply(myVect, myVect)produce an element-by-element output of [ 1, 4, 9, 16] when starting with an array of [1, 2, 3, 4].

Algorithms For Dummies - изображение 58Unfortunately, an element-by-element multiplication can produce incorrect results when working with algorithms. In many cases, what you really need is a dot product, which is the sum of the products of two number sequences. When working with vectors, the dot product is always the sum of the individual element-by-element multiplications and results in a single number. For example, myVect.dot(myVect)results in an output of 30. If you sum the values from the element-by-element multiplication, you find that they do indeed add up to 30. The discussion at https://www.mathsisfun.com/algebra/vectors-dot-product.html tells you about dot products and helps you understand where they might fit in with algorithms. You can learn more about the linear algebra manipulation functions for numpyat https://numpy.org/doc/stable/reference/routines.linalg.html .

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Algorithms For Dummies»

Представляем Вашему вниманию похожие книги на «Algorithms For Dummies» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Algorithms For Dummies»

Обсуждение, отзывы о книге «Algorithms For Dummies» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x