## Functions on arrays of values

| categories: python | tags:

It is common to evaluate a function for a range of values. Let us consider the value of the function $$f(x) = \cos(x)$$ over the range of $$0 < x < \pi$$. We cannot consider every value in that range, but we can consider say 10 points in the range. The nil conveniently creates an array of values.

import numpy as np
print np.linspace(0, np.pi, 10)

[ 0.          0.34906585  0.6981317   1.04719755  1.3962634   1.74532925
2.0943951   2.44346095  2.7925268   3.14159265]


The main point of using the nil functions is that they work element-wise on elements of an array. In this example, we compute the $$\cos(x)$$ for each element of $$x$$.

import numpy as np
x = np.linspace(0, np.pi, 10)
print np.cos(x)

[ 1.          0.93969262  0.76604444  0.5         0.17364818 -0.17364818
-0.5        -0.76604444 -0.93969262 -1.        ]


You can already see from this output that there is a root to the equation $$\cos(x) = 0$$, because there is a change in sign in the output. This is not a very convenient way to view the results; a graph would be better. We use nil to make figures. Here is an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, np.pi, 10)
plt.plot(x, np.cos(x))
plt.xlabel('x')
plt.ylabel('cos(x)')
plt.savefig('images/plot-cos.png')


This figure illustrates graphically what the numbers above show. The function crosses zero at approximately $$x = 1.5$$. To get a more precise value, we must actually solve the function numerically. We use the function nil to do that. More precisely, we want to solve the equation $$f(x) = \cos(x) = 0$$. We create a function that defines that equation, and then use nil to solve it.

from scipy.optimize import fsolve
import numpy as np

def f(x):
return np.cos(x)

sol, = fsolve(f, x0=1.5) # the comma after sol makes it return a float
print sol
print np.pi / 2

1.57079632679
1.57079632679


We know the solution is π/2.