# Python and Numpy

To use the numerical python library numpy we need to import it. As it is commonly used and referenced, it is usually imported as a two letter abbreviation at the top of a Python script:

Python

Next it is worth looking through the library, this can be done by typing either in the script or console, np followed by a dot and then tab:

Python

This will give a large list of entries by alphabetical order (items stating with a capital are listed first)

Scrolling through the list, in the console, we can see the function pi, which will return pi:

We can select it:

And then execute it:

Python
``3.141592653589793``

It then unsurprisingly returns the value of pi. In order to get more information about this command we can type in a question mark followed by the command:

Python
``````Type:        float
String form: 3.141592653589793
Docstring:   Convert a string or number to a floating point number, if possible.``````

This opens up the help and explains briefly how to use the command.

Likewise we can have a look at

Python
``````Type:        float
String form: 2.718281828459045
Docstring:   Convert a string or number to a floating point number, if possible.``````
Python
``2.718281828459045``

There are a number of functions that can use a scalar input, for instance the square root function. It is worthwhile reading the help of these:

Python

The first example the help gives is a row vector, however we can also use a simple positive scalar input for simplicity. The help also gives details about complex numbers and more complicated structures:

``````Call signature:   np.sqrt(*args, **kwargs)
Type:            ufunc
String form:     <ufunc 'sqrt'>
File:            c:\users\pyip\appdata\local\continuum\anaconda3\lib\site-packages\numpy\__init__.py
Docstring:
sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Return the non-negative square-root of an array, element-wise.

Parameters
----------
x : array_like
The values whose square-roots are required.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
y : ndarray
An array of the same shape as `x`, containing the positive
square-root of each element in `x`.  If any element in `x` is
complex, a complex array is returned (and the square-roots of
negative reals are calculated).  If all of the elements in `x`
are real, so is `y`, with negative elements returning ``nan``.
If `out` was provided, `y` is a reference to it.
This is a scalar if `x` is a scalar.

--------
lib.scimath.sqrt
A version which returns complex numbers when given negative reals.

Notes
-----
*sqrt* has--consistent with common convention--as its branch cut the
real "interval" [`-inf`, 0), and is continuous from above on it.
A branch cut is a curve in the complex plane across which a given
complex function fails to be continuous.

Examples
--------
np.sqrt([1,4,9])
array([ 1.,  2.,  3.])

np.sqrt([4, -1, -3+4J])
array([ 2.+0.j,  0.+1.j,  1.+2.j])

np.sqrt([4, -1, numpy.inf])
array([  2.,  NaN,  Inf])
Class docstring:
Functions that operate element by element on whole arrays.

To see the documentation for a specific ufunc, use `info`.  For
example, ``np.info(np.sin)``.  Because ufuncs are written in C
(for speed) and linked into Python with NumPy's ufunc facility,
on a ufunc.

A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.

Calling ufuncs:
===============

op(*x[, out], where=True, **kwargs)
Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.

* Dimensions of length 1 may be prepended to either array.
* Arrays may be repeated along dimensions of length 1.

Parameters
----------
*x : array_like
Input arrays.
out : ndarray, None, or tuple of ndarray and None, optional
Alternate array object(s) in which to put the result; if provided, it
must have a shape that the inputs broadcast to. A tuple of arrays
(possible only as a keyword argument) must have length equal to the
number of outputs; use `None` for uninitialized outputs to be
allocated by the ufunc.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.  Note that if
an uninitialized return array is created via the default ``out=None``,
then the elements where the values are False will remain uninitialized.
**kwargs
For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
r : ndarray or tuple of ndarray
`r` will have the shape that the arrays in `x` broadcast to; if `out` is
provided, it will be returned. If not, `r` will be allocated and
may contain uninitialized values. If the function has more than one
output, then the result will be a tuple of arrays.``````

In our case we can use the function with a scalar input argument of 2:

Python
``1.4142135623730951``

The answer has a sequence of non-converging numbers following the decimal point. It may be useful to round this number, we can look at the round function:

Python
``````Signature:  np.round(a, decimals=0, out=None)
Docstring:
Round an array to the given number of decimals.

--------
around : equivalent function; see for details.
File:      c:\users\pyip\appdata\local\continuum\anaconda3\lib\site-packages\numpy\core\fromnumeric.py
Type:      function``````

Here we are told the first input argument is our array a, in our case our scalar can directly be input:

Python
``1.0``

Note in the expression above, the outside brackets ( ) surround the input arguments of round, with the function round being called from the library np (abbreviated from the full library name numpy). The inside brackets ( ) surround the input arguments of the function sqrt and sqrt is once again a function being called from the library np.

In np.sqrt there is a single input argument, the scalar 2. In np.round there is a single input argument np.sqrt(2) and as only a single input argument was specified for np.round, the default setting is used, i.e. rounding to the nearest integer.

A second input argument to round can be specified as 1 to round to 1 decimal place. In this case the comma , is used to separate out the two input arguments.

Take the time to understand calling functions from the np library using the dot . aswell as the use of ( ) to surround input arguments and the use of , to separate out the input arguments.

Python
``1.4``

If instead we wanted 2 decimal places:

Python
``1.41``

We can also look at the function power. Once again looking up help for this function we can see a description:

Python
``````Call signature:  np.power(*args, **kwargs)
Type:            ufunc
String form:     <ufunc 'power'>
File:            c:\users\pyip\appdata\local\continuum\anaconda3\lib\site-packages\numpy\__init__.py
Docstring:
power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in
`x2`.  `x1` and `x2` must be broadcastable to the same shape. Note that an
integer type raised to a negative integer power will raise a ValueError.

Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
This is a scalar if both `x1` and `x2` are scalars.

--------
float_power : power function that promotes integers to float

Examples
--------
Cube each element in a list.

x1 = range(6)
x1
[0, 1, 2, 3, 4, 5]
np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

Raise the bases to different exponents.

x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
[ 0,  1,  8, 27, 16,  5]])
Class docstring:
Functions that operate element by element on whole arrays.

To see the documentation for a specific ufunc, use `info`.  For
example, ``np.info(np.sin)``.  Because ufuncs are written in C
(for speed) and linked into Python with NumPy's ufunc facility,
on a ufunc.

A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.

Calling ufuncs:
===============

op(*x[, out], where=True, **kwargs)
Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.

* Dimensions of length 1 may be prepended to either array.
* Arrays may be repeated along dimensions of length 1.

Parameters
----------
*x : array_like
Input arrays.
out : ndarray, None, or tuple of ndarray and None, optional
Alternate array object(s) in which to put the result; if provided, it
must have a shape that the inputs broadcast to. A tuple of arrays
(possible only as a keyword argument) must have length equal to the
number of outputs; use `None` for uninitialized outputs to be
allocated by the ufunc.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.  Note that if
an uninitialized return array is created via the default ``out=None``,
then the elements where the values are False will remain uninitialized.
**kwargs
For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
r : ndarray or tuple of ndarray
`r` will have the shape that the arrays in `x` broadcast to; if `out` is
provided, it will be returned. If not, `r` will be allocated and
may contain uninitialized values. If the function has more than one
output, then the result will be a tuple of arrays.``````

In this example we are only looking at scalars, so the following will calculate:

$\displaystyle {{3}^{3}}$

Python
``27``

This can be used also in place of the sqrt function above. Once again we can see that the outside brackets ( ) surround the input arguments of round, with the function round being called from the library np (abbreviated from the full library name numpy). The inside brackets ( ) surround the input arguments of the function power and power is once again a function being called from the library np. There are two input arguments for the function power 2 and 1/2, these are once again separated by a comma , and the inside function and its input arguments i.e. np.power(2,1/2) is an input argument alongside 2 for the outside function np.round, once again separated by a comma.

Python
``````1.41
``````

The power function can also be used to get the cube root or nth root:

Python
``3``