Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Programming Integration – an example of passing functions to functions Wr

ID: 3685442 • Letter: P

Question

Python Programming

Integration – an example of passing functions to functions
Write a function
integrate(f,a,b)
which accepts three arguments f,a and b.
f is the name of a function of one variable, and a and b are two floating point numbers representing points on the x axis.

A call on integrate(f,a,b) returns the definite integral (the area under the curve defined by function evaluated between x=a and x=b.
How?
In function integrate(f,a,b) use a loop to evaluate a series of rectangles whose base is .000001 and whose height is f(x) where x starts at x=a and takes on successive values adding .000001 each time as long as x <b.

Test your function on the following functions:
def line1(x):
return 5
def line2(x):
return x
def square(n):
return x*x
return cube(x):
return x*x*x
For example, integrate(line1, 2.0 ,3.0) should print something very close to 5.

Explanation / Answer

import numpy as np import matplotlib.pyplot as plt from scipy import integrate # random number generator def random(start, amount, a=106, c=1283, m=6075): Ij = start random_list = [] for i in range(amount): Ij = (float(a)*Ij + float(c)) % float(m) random_list.append(Ij/(m-1)) # normalize with m instead of m-1 to receive open domain return np.array(random_list) # define some functions def square(x): return x*x def cube(x): return x*x*x def sinus(x): return np.sin(x) def exponential(x): return np.exp(x) def mc_integral(function, random_numbers): return np.sum(function(random_numbers))/len(random_numbers) functions = [square, cube, sinus, exponential] # compute integrals for various N N_vals = [10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000] diff_vals = {} for function in functions: diff_vals[function] = [] for N in N_vals: print(' N = '+str(N)) xi_arr = random(1337, N) for function in functions: name = function.__name__ mc_val = mc_integral(function, xi_arr) cor_val = integrate.quad(function, 0, 1)[0] diff_val = abs(mc_val - cor_val) print(name+': MC-Wert: '+str(mc_val)+'. Korrekter Wert: '+str(cor_val)+'. Unterschied: '+str(diff_val)) diff_vals[function].append(diff_val) for function in functions: plt.plot(N_vals, diff_vals[function]) plt.xscale('log') plt.yscale('log') plt.show()