Defining Functions#
import numpy as np
Mathematical Functions#
All the standard mathematical functions are available in NumPy:
Function |
NumPy Syntax |
---|---|
\(\sin(x)\) |
|
\(\cos(x)\) |
|
\(\tan(x)\) |
|
\(\tan^{-1}(x)\) |
|
\(e^x\) |
|
\(\ln(x)\) |
|
\(\log_{10}(x)\) |
|
\(\sqrt{x}\) |
|
Let’s compute some examples:
np.cos(np.pi/4)
0.7071067811865476
1/np.sqrt(2)
0.7071067811865475
np.log(2)
0.6931471805599453
np.arctan(1)
0.7853981633974483
np.log10(2)
0.3010299956639812
10**0.3010299956639812
2.0
Defining Functions#
We can define our own custom functions. For example, let’s write a function called fun
which takes input parameters x
and y
and returns the value
def fun(x,y):
value = np.sqrt(x**2 + y**2)
return value
Let’s make some key observations about the construction:
def
is a keyword that starts the function definitionfun
is the name of the functionthe input parameters are listed within parentheses
(x,y)
def
statement ends with a colon:
body of the function is indented 4 spaces
output value follows the
return
keyword
fun(1,2)
2.23606797749979
fun(-1,1)
1.4142135623730951
lambda
Functions#
We can also create simple functions using the lambda
keyword. For example, let’s create the function:
f = lambda x: 1/(1 + x**2)
The keyword lambda
starts the function definition, the input variable is x
and the formula for the funciton output follows a colon :
.
Compute some values of \(f(x)\):
f(0)
1.0
f(1)
0.5
f(2)
0.2
Now let’s construct the function
h = lambda x,y: np.sqrt(x**2 + y**2)
h(1,2)
2.23606797749979
h(-1,1)
1.4142135623730951
Lambda functions are helpful for defining simple functions but longer more complicated functions require the def
construction.