Added SciPy/NumPy/Matplotlib examples

Added a few more examples for each package, and moved them to the
preface to improve the flow of the g-h chapter.
This commit is contained in:
Roger Labbe 2018-01-01 14:16:39 -08:00
parent d0f6aeb4d7
commit 44c280f65b
2 changed files with 927 additions and 489 deletions

View File

@ -25,7 +25,245 @@
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"outputs": [
{
"data": {
"text/html": [
"<style>\n",
"@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');\n",
"@import url('http://fonts.googleapis.com/css?family=Lora');\n",
"\n",
".CodeMirror pre {\n",
" font-family: 'Source Code Pro', Consolas, monocco, monospace;\n",
"}\n",
" div.cell{\n",
" //width: 950px;\n",
" margin-left: 0% !important;\n",
" margin-right: auto;\n",
" }\n",
" div.text_cell_render{\n",
" font-family: 'Lora';\n",
" line-height: 125%;\n",
" font-size: 100%;\n",
" text-align: justify;\n",
" text-justify:inter-word;\n",
" }\n",
" div.text_cell code {\n",
" background: transparent;\n",
" color: #000000;\n",
" font-weight: 400;\n",
" font-size: 11pt;\n",
" font-family: 'Source Code Pro', Consolas, monocco, monospace;\n",
" }\n",
" h1 {\n",
" font-family: 'Open sans',verdana,arial,sans-serif;\n",
"\t}\n",
"\n",
" div.input_area {\n",
" background: #F6F6F9;\n",
" border: 1px solid #586e75;\n",
" }\n",
"\n",
" .text_cell_render h1 {\n",
" font-weight: 200;\n",
" font-size: 30pt;\n",
" line-height: 100%;\n",
" color:#c76c0c;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 1em;\n",
" display: block;\n",
" white-space: wrap;\n",
" text-align: left;\n",
" }\n",
" h2 {\n",
" font-family: 'Open sans',verdana,arial,sans-serif;\n",
" text-align: left;\n",
" }\n",
" .text_cell_render h2 {\n",
" font-weight: 200;\n",
" font-size: 16pt;\n",
" font-style: italic;\n",
" line-height: 100%;\n",
" color:#c76c0c;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 1.5em;\n",
" display: block;\n",
" white-space: wrap;\n",
" text-align: left;\n",
" }\n",
" h3 {\n",
" font-family: 'Open sans',verdana,arial,sans-serif;\n",
" }\n",
" .text_cell_render h3 {\n",
" font-weight: 200;\n",
" font-size: 14pt;\n",
" line-height: 100%;\n",
" color:#d77c0c;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 2em;\n",
" display: block;\n",
" white-space: wrap;\n",
" text-align: left;\n",
" }\n",
" h4 {\n",
" font-family: 'Open sans',verdana,arial,sans-serif;\n",
" }\n",
" .text_cell_render h4 {\n",
" font-weight: 100;\n",
" font-size: 14pt;\n",
" color:#d77c0c;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 0.5em;\n",
" display: block;\n",
" white-space: nowrap;\n",
" }\n",
" h5 {\n",
" font-family: 'Open sans',verdana,arial,sans-serif;\n",
" }\n",
"\n",
" .text_cell_render h5 {\n",
" font-weight: 200;\n",
" font-style: normal;\n",
" color: #1d3b84;\n",
" font-size: 16pt;\n",
" margin-bottom: 0em;\n",
" margin-top: 0.5em;\n",
" display: block;\n",
" white-space: nowrap;\n",
" }\n",
" div.output_subarea.output_text.output_pyout {\n",
" overflow-x: auto;\n",
" overflow-y: visible;\n",
" max-height: 5000000px;\n",
" }\n",
" div.output_subarea.output_stream.output_stdout.output_text {\n",
" overflow-x: auto;\n",
" overflow-y: visible;\n",
" max-height: 5000000px;\n",
" }\n",
" div.output_wrapper{\n",
" margin-top:0.2em;\n",
" margin-bottom:0.2em;\n",
"}\n",
"\n",
" code{\n",
" font-size: 6pt;\n",
"\n",
" }\n",
" .rendered_html code{\n",
" background-color: transparent;\n",
" }\n",
" ul{\n",
" margin: 2em;\n",
" }\n",
" ul li{\n",
" padding-left: 0.5em;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 0.5em;\n",
" }\n",
" ul li li{\n",
" padding-left: 0.2em;\n",
" margin-bottom: 0.2em;\n",
" margin-top: 0.2em;\n",
" }\n",
" ol{\n",
" margin: 2em;\n",
" }\n",
" ol li{\n",
" padding-left: 0.5em;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 0.5em;\n",
" }\n",
" ul li{\n",
" padding-left: 0.5em;\n",
" margin-bottom: 0.5em;\n",
" margin-top: 0.2em;\n",
" }\n",
" a:link{\n",
" color:#447adb;\n",
" }\n",
" a:visited{\n",
" color: #1d3b84;\n",
" }\n",
" a:hover{\n",
" color: #1d3b84;\n",
" }\n",
" a:focus{\n",
" color:#447adb;\n",
" }\n",
" a:active{\n",
" font-weight: bold;\n",
" color:#447adb;\n",
" }\n",
" .rendered_html :link {\n",
" text-decoration: underline;\n",
" }\n",
" .rendered_html :hover {\n",
" text-decoration: none;\n",
" }\n",
" .rendered_html :visited {\n",
" text-decoration: none;\n",
" }\n",
" .rendered_html :focus {\n",
" text-decoration: none;\n",
" }\n",
" .rendered_html :active {\n",
" text-decoration: none;\n",
" }\n",
" .warning{\n",
" color: rgb( 240, 20, 20 )\n",
" }\n",
" hr {\n",
" color: #f3f3f3;\n",
" background-color: #f3f3f3;\n",
" height: 1px;\n",
" }\n",
" blockquote{\n",
" display:block;\n",
" background: #fcfcfc;\n",
" border-left: 5px solid #c76c0c;\n",
" font-family: 'Open sans',verdana,arial,sans-serif;\n",
" width:680px;\n",
" padding: 10px 10px 10px 10px;\n",
" text-align:justify;\n",
" text-justify:inter-word;\n",
" }\n",
" blockquote p {\n",
" margin-bottom: 0;\n",
" line-height: 125%;\n",
" font-size: 100%;\n",
" }\n",
"</style>\n",
"<script>\n",
" MathJax.Hub.Config({\n",
" TeX: {\n",
" extensions: [\"AMSmath.js\"],\n",
" equationNumbers: { autoNumber: \"AMS\", useLabelIds: true}\n",
" },\n",
" tex2jax: {\n",
" inlineMath: [ ['$','$'], [\"\\\\(\",\"\\\\)\"] ],\n",
" displayMath: [ ['$$','$$'], [\"\\\\[\",\"\\\\]\"] ]\n",
" },\n",
" displayAlign: 'center', // Change this to 'center' to center equations.\n",
" \"HTML-CSS\": {\n",
" scale:95,\n",
" availableFonts: [],\n",
" preferredFont:null,\n",
" webFont: \"TeX\",\n",
" styles: {'.MathJax_Display': {\"margin\": 4}}\n",
" }\n",
" });\n",
"</script>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#format the book\n",
"from book_format import load_style\n",
@ -170,6 +408,620 @@
"Admittedly this is a cumbersome interface to a book. I am following in the footsteps of several other projects that are re-purposing Jupyter Notebook to generate entire books. I feel the slight annoyances have a huge payoff - instead of having to download a separate code base and run it in an IDE while you try to read a book, all of the code and text is in one place. If you want to alter the code, you may do so and immediately see the effects of your change. If you find a bug, you can make a fix, and push it back to my repository so that everyone in the world benefits. And, of course, you will never encounter a problem I face all the time with traditional books - the book and the code are out of sync with each other, and you are left scratching your head as to which source to trust."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Jupyter\n",
"\n",
"First, some words about using Jupyter Notebooks with this book. This book is interactive. If you want to run code examples, and especially if you want to see animated plots, you will need to run the code cells. I cannot teach you everything about Jupyter Notebooks. However, a few things trip readers up. You can go to http://jupyter.org/ for detailed documentation.\n",
"\n",
"First, you must always run the topmost code cell, the one with the comment `#format the book`. It is directly above. This does not just set up formatting, which you might not care about, but it also loads some necessary modules and makes some global settings regarding plotting and printing. So, always run this cell unless you are just passively reading. The import from `__future__` helps Python 2.7 work like Python 3.X. Division of integers will return a `float` (`3/10 == 0.3`) instead of an `int` (`3/10 == 0`), and printing requires parens: `print(3)`, not `print 3`. The line\n",
"\n",
"```python\n",
"%matplotlib inline\n",
"```\n",
"causes plots to be displayed inside the notebook. Matplotlib is a plotting package which is described below. For reasons I don't understand the default behavior of Jupyter Notebooks is to generate plots in an external window. \n",
"\n",
"The percent sign in `%matplotlib` is used for IPython *magic* - these are commands to the kernel to do things that are not part of the Python language. There are many useful magic commands, and you can read about them here: http://ipython.readthedocs.io/en/stable/interactive/magics.html \n",
"\n",
"Running the code inside a cell is easy. Click on it so that it has focus (a box will be drawn around it), and then press CTRL-Enter. \n",
"\n",
"Second, cells must be run in order. I break problems up over several cells; if you try to just skip down and run the tenth code cell it almost certainly won't work. If you haven't run anything yet just choose *Run All Above* from the **Cell** menu item. That's the easiest way to ensure everything has been run.\n",
"\n",
"Once cells are run you can often jump around and rerun cells in different orders, but not always. I'm trying to fix this, but there is a tradeoff. I'll define a variable in cell 10 (say), and then run code that modifies that variable in cells 11 and 12. If you go back and run cell 11 again the variable will have the value that was set in cell 12, and the code expects the value that was set in cell 10. So, occasionally you'll get weird results if you run cells out of order. My advise is to backtrack a bit, and run cells in order again to get back to a proper state. It's annoying, but the interactive aspect of Jupyter notebooks more than makes up for it. Better yet, submit an issue on GitHub so I know about the problem and fix it!\n",
"\n",
"Finally, some readers have reported problems with the animated plotting features in some browsers. I have not been able to reproduce this. In parts of the book I use the `%matplotlib notebook` magic, which enables interactive plotting. If these plots are not working for you, try changing this to read `%matplotlib inline`. You will lose the animated plotting, but it seems to work on all platforms and browsers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## SciPy, NumPy, and Matplotlib\n",
"\n",
"SciPy is a open source collection of software for mathematics. Included in SciPy are NumPy, which provides array objects, linear algebra, random numbers, and more. Matplotlib provides plotting of NumPy arrays. SciPy's modules duplicate some of the functionality in NumPy while adding features such as optimization, image processing, and more.\n",
"\n",
"To keep my efforts for this book managable I have elected to assume that you know how to program in Python, and that you also are familiar with these packages. Nonetheless, I will take a few moments to illustrate a few features of each; realistically you will have to find outside sources to teach you the details. The home page for SciPy, https://scipy.org, is the perfect starting point, though you will soon want to search for relevant tutorials and/or videos.\n",
"\n",
"NumPy, SciPy, and Matplotlib do not come with the default Python distribution; see the *Installation* Appendix if you do not have them installed.\n",
"\n",
"I use NumPy's array data structure throughout the book, so let's learn about them now. I will teach you enough to get started; refer to NumPy's documentation if you want to become an expert.\n",
"\n",
"`numpy.array` implements a one or more dimensional array. Its type is `numpy.ndarray`, and we will refer to this as an ndarray for short. You can construct it with any list-like object. The following constructs a 1-D array from a list:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'numpy.ndarray'>\n"
]
},
{
"data": {
"text/plain": [
"array([1, 2, 3])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy as np\n",
"x = np.array([1, 2, 3])\n",
"print(type(x))\n",
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It has become a industry standard to use `import numpy as np`. \n",
"\n",
"You can also use tuples:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([4, 5, 6])"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = np.array((4,5,6))\n",
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create multidimensional arrays with nested brackets:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1 2 3]\n",
" [4 5 6]]\n"
]
}
],
"source": [
"x = np.array([[1, 2, 3],\n",
" [4, 5, 6]])\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can create arrays of 3 or more dimensions, but we have no need for that here, and so I will not elaborate.\n",
"\n",
"By default the arrays use the data type of the values in the list; if there are multiple types then it will choose the type that most accurately represents all the values. So, for example, if your list contains a mix of `int` and `float` the data type of the array would be of type `float`. You can override this with the `dtype` parameter."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 1.0 2.0 3.0]\n"
]
}
],
"source": [
"x = np.array([1, 2, 3], dtype=float)\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can access the array elements using subscript location:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6\n"
]
}
],
"source": [
"x = np.array([[1, 2, 3],\n",
" [4, 5, 6]])\n",
"\n",
"print(x[1,2])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can access a column or row by using slices. A colon (:) used as a subscript is shorthand for all data in that row or column. So `x[:,0]` returns an array of all data in the first column (the 0 specifies the first column):"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 4])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[:, 0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can get the second row with:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([4, 5, 6])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[1, :]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the last two elements of the second row with:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([5, 6])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[1, 1:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As with Python `list`s, you can use negative indexes to refer to the end of the array. -1 refers to the last index. So another way to get the last two elements of the second (last) row would be:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([5, 6])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[-1, -2:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can perform matrix addition with the `+` operator, but matrix multiplication requires the `dot` method or function. The `*` operator performs element-wise multiplication, which is **not** what you want for linear algebra."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"abddition:\n",
" [[ 2.0 4.0]\n",
" [ 6.0 8.0]]\n",
"\n",
"element-wise multiplication\n",
" [[ 1.0 4.0]\n",
" [ 9.0 16.0]]\n",
"\n",
"multiplication\n",
" [[ 7.0 10.0]\n",
" [ 15.0 22.0]]\n",
"\n",
"dot is also a member of np.array\n",
" [[ 7.0 10.0]\n",
" [ 15.0 22.0]]\n"
]
}
],
"source": [
"x = np.array([[1., 2.],\n",
" [3., 4.]])\n",
"print('abddition:\\n', x + x)\n",
"print('\\nelement-wise multiplication\\n', x * x)\n",
"print('\\nmultiplication\\n', np.dot(x, x))\n",
"print('\\ndot is also a member of np.array\\n', x.dot(x))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python 3.5 introduced the `@` operator for matrix multiplication.\n",
"\n",
"```python\n",
"x @ x\n",
"\n",
"[[ 7.0 10.0]\n",
" [ 15.0 22.0]]\n",
"```\n",
"\n",
"This will only work is you are running Python 3.5 or later. So, as much as I prefer this notation to `np.dot(x, x)` I will not use it in this book."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can get the transpose with `.T`, and the inverse with `numpy.linalg.inv`. The SciPy package also provides the inverse function."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"transpose\n",
" [[ 1.0 3.0]\n",
" [ 2.0 4.0]]\n",
"\n",
"NumPy ninverse\n",
" [[ -2.0 1.0]\n",
" [ 1.5 -0.5]]\n",
"\n",
"SciPy inverse\n",
" [[ -2.0 1.0]\n",
" [ 1.5 -0.5]]\n"
]
}
],
"source": [
"import scipy.linalg as linalg\n",
"print('transpose\\n', x.T)\n",
"print('\\nNumPy ninverse\\n', np.linalg.inv(x))\n",
"print('\\nSciPy inverse\\n', linalg.inv(x))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are helper functions like `zeros` to create a matrix of all zeros, `ones` to get all ones, and `eye` to get the identity matrix. If you want a multidimensional array, use a tuple to specify the shape."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"zeros\n",
" [ 0.0 0.0 0.0 0.0 0.0 0.0 0.0]\n",
"\n",
"zeros(3x2)\n",
" [[ 0.0 0.0]\n",
" [ 0.0 0.0]\n",
" [ 0.0 0.0]]\n",
"\n",
"eye\n",
" [[ 1.0 0.0 0.0]\n",
" [ 0.0 1.0 0.0]\n",
" [ 0.0 0.0 1.0]]\n"
]
}
],
"source": [
"print('zeros\\n', np.zeros(7))\n",
"print('\\nzeros(3x2)\\n', np.zeros((3, 2)))\n",
"print('\\neye\\n', np.eye(3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have functions to create equally spaced data. `arange` works much like Python's `range` function, except it returns a NumPy array. `linspace` works slightly differently, you call it with `linspace(start, stop, num)`, where `num` is the length of the array that you want."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,\n",
" 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.arange(0, 2, 0.1)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0.0, 0.105, 0.211, 0.316, 0.421, 0.526, 0.632, 0.737,\n",
" 0.842, 0.947, 1.05, 1.16, 1.26, 1.37, 1.47, 1.58,\n",
" 1.68, 1.79, 1.89, 2.0])"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.linspace(0, 2, 20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's plot some data. For the most part it is very simple. Matplotlib contains a plotting library `pyplot`. It is industry standard to import it as `plt`. Once imported, plot numbers by calling `plt.plot` with a list or array of numbers. If you make multiple calls it will plot multiple series, each with a different color."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<matplotlib.lines.Line2D at 0x21b07a17780>]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"a = np.array([6, 3, 5, 2, 4, 1])\n",
"plt.plot([1, 4, 2, 5, 3, 6])\n",
"plt.plot(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The output `[<matplotlib.lines.Line2D at 0x2ba160bed68>]` is because `plt.plot` returns the object that was just created. Ordinarily we do not want to see that, so I add a `;` to my last plotting command to suppress that output.\n",
"\n",
"By default `plot` assumes that the x-series is incremented by one. You can provide your own x-series by passing in both x and y."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"plt.plot(np.arange(0,1, 0.1), [1,4,3,2,6,4,7,3,4,5]);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many more features to these packages which I use in this book. Normally I will introduce them without explanation, trusting that you can infer the usage from context, or search online for an explanation. As always, if you are unsure, create a new cell in the Notebook or fire up a Python console and experiment!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise - Create arrays\n",
"\n",
"I want you to create a NumPy array of 10 elements with each element containing 1/10. There are several ways to do this; try to implement as many as you can think of. "
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# your solution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Solution\n",
"\n",
"Here are three ways to do this. The first one is the one I want you to know. I used the '/' operator to divide all of the elements of the array with 10. We will shortly use this to convert the units of an array from meters to km."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]\n",
"[ 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]\n",
"[ 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]\n"
]
}
],
"source": [
"print(np.ones(10) / 10.)\n",
"print(np.array([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]))\n",
"print(np.array([.1]*10))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is one I haven't covered yet. The function `numpy.asarray()` will convert its argument to an ndarray if it isn't already one. If it is, the data is unchanged. This is a handy way to write a function that can accept either Python lists or ndarrays, and it is very efficient if the type is already ndarray as nothing new is created."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 0.1 0.2 0.3]\n",
"[ 0.4 0.5 0.6]\n"
]
}
],
"source": [
"def one_tenth(x):\n",
" x = np.asarray(x)\n",
" return x / 10.\n",
"\n",
"print(one_tenth([1, 2, 3])) # I work!\n",
"print(one_tenth(np.array([4, 5, 6]))) # so do I!"
]
},
{
"cell_type": "markdown",
"metadata": {},

File diff suppressed because one or more lines are too long