<jupyter_start><jupyter_text>Integration Exercise 1  Imports<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate<jupyter_output><empty_output><jupyter_text>Trapezoidal rule The [trapezoidal](http://en.wikipedia.org/wiki/Trapezoidal_rule) rule generates a numerical approximation to the 1d integral:$$ I(a,b) = \int_a^b f(x) dx $$by dividing the interval $[a,b]$ into $N$ subdivisions of length $h$:$$ h = (b-a)/N $$Note that this means the function will be evaluated at $N+1$ points on $[a,b]$. The main idea of the trapezoidal rule is that the function is approximated by a straight line between each of these points.Write a function `trapz(f, a, b, N)` that performs trapezoidal rule on the function `f` over the interval $[a,b]$ with `N` subdivisions (`N+1` points).<jupyter_code>def trapz(f, a, b, N):
    """Integrate the function f(x) over the range [a,b] with N points."""
    
    N = N+1
    a = a
    b = b
    h = (b-a)/N
    
    k1 = np.arange(a, b, N)
    k2 = np.arange(a,b,)
def trapz(f, a, b, N):
    """Integrate the function f(x) over the range [a,b] with N points."""
    
    N = N+1
    a = a
    b = b
    h = (b-a)/N
    
    k = np.arange(1,N)
    return h*(0.5*f(a) + 0.5*f(b) + f(a+k*h).sum())
f = lambda x: x**2
g = lambda x: np.sin(x)
I = trapz(f, 0, 1, 1000)
assert np.allclose(I, 0.33333349999999995)
J = trapz(g, 0, np.pi, 1000)
assert np.allclose(J, 1.9999983550656628)<jupyter_output><empty_output><jupyter_text>Now use `scipy.integrate.quad` to integrate the `f` and `g` functions and see how the result compares with your `trapz` function. Print the results and errors.<jupyter_code>RYANISAWESOME = integrate.quad(f,0,1)[0]
RYANISSTILLAWESOME = integrate.quad(g,0,np.pi)[0]

error1 = np.abs(I - RYANISAWESOME) / RYANISAWESOME

error2 = np.abs(J - RYANISSTILLAWESOME) / RYANISSTILLAWESOME

print("{0} vs scipy.integrate.quad error = {1}".format("I",error1))
print("{0} vs scipy.integrate.quad error = {1}".format("J",error2))
assert True # leave this cell to grade the previous one<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14346793349168646, 'fraction_numerical': 0.03467933491686461, 'mean_word_length': 4.225806451612903, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '379964', 'license': 'MIT', 'n_tokens_mistral': 883, 'n_tokens_neox': 818, 'n_words': 243, 'path': 'assignments/assignment09/IntegrationEx01.ipynb', 'repo_name': 'LimeeZ/phys292-2015-work', 'size': '2105'}