Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import pandas
- from pandas import DataFrame
- # pandas.set_option('display.height', 5000)
- pandas.set_option('display.max_rows', 500)
- pandas.set_option('display.max_columns', 500)
- pandas.set_option('display.width', 180)
- print("Choose function to integrate:")
- print(DataFrame.from_records([
- ["cos(x)"],
- ["x ^ 4"],
- ["x ^ 3"],
- ["x ^ 2"],
- ["x"],
- ["sin(x)"]
- ]))
- CHOICE = int(input())
- print("You choose to integrate", end=' ')
- if CHOICE == 0:
- print("cos(x)")
- f = math.cos
- f1 = math.sin
- elif CHOICE == 1:
- print("x ^ 4")
- f = lambda x: x ** 4
- f1 = lambda x: x ** 5 / 5
- elif CHOICE == 2:
- print("x ^ 3")
- f = lambda x: x ** 3
- f1 = lambda x: x ** 4 / 4
- elif CHOICE == 3:
- print("x ^ 2")
- f = lambda x: x ** 2
- f1 = lambda x: x ** 3 / 3
- elif CHOICE == 4:
- print("x")
- f = lambda x: x
- f1 = lambda x: x ** 2 / 2
- elif CHOICE == 5:
- print("sin(x)")
- f = lambda x: math.sin(x)
- f1 = lambda x: -math.cos(x)
- print ("Enter A and B - boudaries of the segment of integration.")
- a, b = (lambda x: (float(x[0]), float(x[1])))(input().split())
- print("Enter m - number of division segments.")
- m = int(input())
- table_xk = [a + (b - a) * i / m for i in range(0, m + 1) ]
- # print("Generated table of x_k with values of f.")
- # print(DataFrame.from_records([
- # ["x_k"] + table_xk,
- # ["f(x_k)"] + [f(xi) for xi in table_xk],
- # ]))
- h = (b - a) / m
- def rectangular_formula(f, h, table_xk):
- val = zip(table_xk, table_xk[1:])
- return h * sum([ f((c + d) / 2) for c, d in val ])
- def trapez_formula(f, h, table_xk):
- f_val = [f(xk) for xk in table_xk]
- f_val = zip(f_val, f_val[1:])
- return h * sum([ (c + d) / 2 for c, d in f_val ])
- def simps_formula(f, h, table_xk):
- x_val = zip(table_xk, table_xk[1:])
- x_val = [ [xk, (xk + xk1) / 2, xk1] for xk, xk1 in x_val ]
- return h / 6 * sum([ f(c) + f(d) * 4 + f(e) for c,d,e in x_val ])
- f_int = f1(b) - f1(a)
- rec = rectangular_formula(f, h, table_xk)
- trap = trapez_formula(f, h, table_xk)
- simz = simps_formula(f, h, table_xk)
- print('Real integration value is', f_int)
- print('Rectangular formula gives value', rec, 'and error', abs(rec - f_int))
- print('Trapez formula gives value', trap, 'and error', abs(trap - f_int))
- print('Simps formula gives value', simz, 'and error', abs(simz - f_int))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement