• API
• FAQ
• Tools
• Archive
SHARE
TWEET Untitled a guest Sep 18th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. from sympy import *
2. from sympy.parsing.sympy_parser import parse_expr
3.
4. x, y, n = symbols('x y n')
5.
6. def simpsons_rule(f, lower_bound, upper_bound, num_intervals):
7.     '''
8.     returns the approximation of an integral
9.     f = the function whos integral is to be approximated
10.     lower_bound = the lower bound of the integral
11.     upper_bound = the upper bound of the integral
12.     num_intervals = the number of intervals to calculate underneath the curve
13.     '''
14.     approximation = f.subs(x, lower_bound)
15.     delta_x = (upper_bound - lower_bound) / num_intervals
16.     this_x_value = lower_bound + delta_x
17.     #the second coefficient of the formula is 4
18.     coefficient = 4
19.     for _ in range(num_intervals - 1):
20.         approximation = approximation + coefficient * f.subs(x, this_x_value)
21.         this_x_value = this_x_value + delta_x
22.         #the coefficients of the formula then alternate between 2 and 4 except the last one
23.         if coefficient == 4:
24.             coefficient = 2
25.         else:
26.             coefficient = 4
27.     return (delta_x / 3 * (approximation + f.subs(x, upper_bound))).evalf()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top