For an assignment, I am trying to find the area function F(X)
between the range from a
to b
, [a,b]
.
Using calculus, this wouldn't be so hard. I did base this on the theorems of calculus to find the area and worked my way around it to reach certain parts of code, like this:
Note: I am using f = x**2
for testing.
def integrate(a,b,tolerance_level):
firsttrapezoid = simpleIntegrate(a,b)
secondtrapezoid = simpleIntegrate(a,b/2) + simpleIntegrate(b/2,b)
error_range = abs(firsttrapezoid - secondtrapezoid)
if error_range < tolerance_level:
return secondtrapezoid
else:
return integrate(a, b/2, tolerance_level/2) + integrate(b/2, b, tolerance_level/2)
def simpleIntegrate(a,b):
return (b-a)*(f(a)+f(b))/2
def f(x):
f = x**2
return f
result = integrate(0,5,0.0001)
print(result)
The problem is, I should get a value around 41, but the value I get is around 44.
change b/2
to the midpoint between a and b which is (a+b)/2
def integrate(a, b, tolerance_level):
firsttrapezoid = simpleIntegrate(a, b)
secondtrapezoid = simpleIntegrate(a, (a + b) / 2) + simpleIntegrate((a + b) / 2, b)
error_range = abs(firsttrapezoid - secondtrapezoid)
if error_range <= tolerance_level:
return secondtrapezoid
else:
return integrate(a, (a + b) / 2, tolerance_level / 2) + integrate((a + b) / 2, b, tolerance_level / 2)
def simpleIntegrate(a, b):
return (b - a) * (f(a) + f(b)) / 2
def f(x):
f = x ** 2
return f
def intf(x):
int_f = (x ** 3) / 3
return int_f
a = 0
b = 5
tolerance = 0.0001
result = integrate(a, b, tolerance)
exactly = intf(b) - intf(a)
error = abs(exactly-result)
print("aprox: {approx} exactly: {exactly} error:{error} max error:{max_error}"
.format(approx=result, exactly=exactly, error=error, max_error=tolerance))
Output:
aprox: 41.66668653488159 exactly: 41.666666666666664 error:1.9868214927498684e-05 max error:0.0001