Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # First we make a function for the Trapezoid rule
- def trapezoid(f, a, b, N):
- n = 0
- sum = 0
- d = (b-a)/N
- xi = a
- xj = a+d
- while n < N:
- sum += (b-a)/(2*N)*(f(xi) + f(xj))
- xi += d
- xj += d
- n += n
- return sum
- # Secondly we make a function for Simpson's rule
- def simpson(f,a,b,N):
- n = 0
- sum = 0
- d = (b-a)/N
- xi = a
- xj = a+d
- while n < N:
- sum += (b-a)/(6*N)*(f(xi) + 4*f((xi + xj)/2) +f(xj))
- xi += d
- xj += d
- n += n
- return sum
- # These two functions are fine and all, but it helpful to defin two more functions for these
- # two functions that allow us to lot them for later. Further more, this function will call
- # the simple() command with a given value of k in order to minimize error with array while in the loop
- def formatDataTrap(f,a,b,k):
- resultArray = np.array([])
- for k in k:
- result = trapezoid(f,a,b,k)
- resultArray = np.append(resultArray, result)
- return resultArray
- def formatDataSimpson(f,a,b,k):
- resultArray = np.array([])
- for k in k:
- result = simpson(f,a,b,k)
- resultArray = np.append(resultArray, result)
- return resultArray
- # First we work with t^3
- f1 = lambda x: x**3
- true1 = 1/4 #This is what the actual integral evaluates to
- i = np.arange(2, 20, 1)
- k = 2**i
- eps = np.finfo(np.double).eps
- errorTrap = lambda k: -np.log10(abs(true1-formatDataTrap(f1,0,1,k))+eps)
- errorSimpson = lambda k: -np.log10(abs(true1-formatDataSimpson(f1,0,1,k))+eps)
- plt.plot(k, errorTrap(k), "r", k, errorSimpson(k), 'b')
- plt.xlabel('N spacings')
- plt.ylabel('Negative Logarithmic Error')
- plt.title('Error for the function x**3')
- plt.show()
- # Since the method is roughly the same for the other two functions,
- # we can easily copy and paste the code to solve for each of these.
- f2 = lambda x: 1/(1+x**2)
- true2 = 2*np.arctan(2) #This is what the actual integral evaluates to
- errorTrap = lambda k: -np.log10(abs(true2-formatDataTrap(f2,-2,2,k))+eps)
- errorSimpson = lambda k: -np.log10(abs(true2-formatDataSimpson(f2,-2,2,k))+eps)
- plt.plot(k, errorTrap(k), "r", k, errorSimpson(k), 'b')
- plt.xlabel('N spacings')
- plt.ylabel('Negative Logarithmic Error')
- plt.title('Error for the function 1/(1+x**2)')
- plt.show()
- f3 = lambda x: np.cos(10**5*x)
- true3 = 10**(-5)*np.sin(10**5) #This is what the actual integral evaluates to
- errorTrap = lambda k: -np.log10(abs(true3-formatDataTrap(f3, 0, 1,k))+eps)
- errorSimpson = lambda k: -np.log10(abs(true3-formatDataSimpson(f3,0,1,k))+eps)
- plt.plot(k, errorTrap(k), "r", k, errorSimpson(k), 'b')
- plt.xlabel('N spacings')
- plt.ylabel('Negative Logarithmic Error')
- plt.title('Error for the function cos(10**5*x)')
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement