Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- def f(x):
- return math.sqrt(0.2*x)*math.cos(0.02*x)
- def left_rect(fx: list, dx: float):
- s = 0.0
- for i in range(0, len(fx)-1):
- s += fx[i]
- return s*dx
- def right_rect(xi: list, dx: float):
- return 0
- s = 0.0
- for i in range(1, len(fx)-1):
- s += fx[i]
- return s*dx
- def trapezoid(xi: list, dx: float):
- return 0
- s = 0.0
- for i in range(0, len(fx)-2):
- s += (fx[i]+fx[i+1])/2
- return s*dx
- def simpson(xi: list, dx: float):
- return 0
- s = 0.0
- for x in xi:
- s += dx/6 * ( f(x) + 4*f(x+dx/2) + f(x+dx) )
- return s*dx
- iterations = [4,20,100,400]
- xmin = 1
- xmax = 3
- print('\n\tleft\t\tright\t\ttrapezoid\tsimpson')
- fx = []
- for i in range(len(iterations)):
- fx.clear
- n = iterations[i]
- dx = (xmax - xmin)/n
- x = xmin
- for i in range(n+1):
- fx.append(f(x))
- x += dx
- #print(left_rect(fx,dx))
- #print(n,' --- ',xi)
- print(f'n={n}\t{left_rect(fx,dx):.10f}\t{right_rect(fx,dx):.10f}\t{trapezoid(fx,dx):.10f}\t{simpson(fx,dx):.10f}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement