Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import json
- class Integral:
- EPS = 0.1
- def __init__(self, function):
- self.integral_function = function
- def definite_integral(self, a: float, b: float) -> float:
- result = self.definite_integral_extended(a, b)
- return min([(value["RichardsonError"], value["Value"]) for key, value in result["Result"].items()])[1]
- def definite_integral_extended(self, a: float, b: float):
- result = {"From": a, "To": b, "Result": {}}
- def convergence(richardsonCharacteristic: int, countMethod):
- n = 1
- integral_n = 0
- integral_2n = 0
- richardson_extrapolation_error = 1
- idx = 0
- while richardson_extrapolation_error > Integral.EPS:
- n *= 2
- integral_n = countMethod(a, b, n) if integral_2n == 0 else integral_2n
- integral_2n = countMethod(a, b, 2*n)
- richardson_extrapolation_error = abs(integral_2n - integral_n) / (2**richardsonCharacteristic - 1)
- idx += 1
- return {"RichardsonCharacteristic": richardsonCharacteristic,
- "RichardsonError": richardson_extrapolation_error,
- "Iterations": idx + 1,
- "Value": integral_2n}
- result["Result"]["RectangleMethod"] = convergence(2, self.__rectangleMethod)
- result["Result"]["TrapezoidMethod"] = convergence(2, self.__trapezoidMethod)
- result["Result"]["SimpsonMethod"] = convergence(4, self.__simpsonMethod)
- return result
- def __rectangleMethod(self, a: float, b: float, n: int):
- h = Integral.__height(a, b, n)
- summ = 0
- for i in range(1, n + 1): summ += self.integral_function(a + (i - 0.5) * h)
- return summ * h
- def __trapezoidMethod(self, a: float, b: float, n: int):
- h = Integral.__height(a, b, n)
- summ = 0
- for i in range(1, n): summ += self.integral_function(a + i * h)
- return h * ((self.integral_function(a) + self.integral_function(b)) / 2 + summ)
- def __simpsonMethod(self, a: float, b: float, n: int):
- h = Integral.__height(a, b, n)
- summ = 0
- for i in range(1, n + 1):
- summ += self.integral_function(a + (i - 1) * h) + 4 * self.integral_function(a + (i - 0.5) * h) + \
- self.integral_function(a + i * h)
- return summ * h / 6
- @staticmethod
- def __height(a: float, b: float, n: int): return (b-a)/n
- if __name__ == '__main__':
- integral = Integral(lambda x: 0.25*x*(math.e**(x**2/2)))
- print(json.dumps(integral.definite_integral_extended(0, 2), indent=4))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement