In [1]:
import numpy as np
In [2]:
def f(x):
return 3*x**2 - 2
interval = np.arange(1, 4, 0.5)
print(interval)
We imported "numpy" (a numerical python package) to have access to a lot of useful methods (functions). In particular, I want the arange method which will create a partition of an interval $[a, b]$ into equally spaced subintervals.
I defined a function $f(x) = 3x^2 - 2$. Notice the use of the double asterix for exponentiation.
I used this method "arange" to create an interval which I called "interval". Note that by default "arange" creates a partition of left endpoints of subintervals. One of the nice things about these arrays of numbers is that we can apply functions to them as a whole as the examples below illustrate.
In [3]:
print(interval + 0.5) # Add 0.5 to each element of the array
In [4]:
print(interval * 2) # Multiply each element of the array by 2
In [5]:
print(interval**2) # Square each element of the array
In [6]:
print(f(interval)) # Apply the function f to each element of the array
We can sum all the elements of an array with the "sum" function as shown below.
In [7]:
print(sum(f(interval))) # Riemann sum
In []: