I am new to Python and have no way how to find the area under a curve given a function. If my function is for example 3x^2+2x+11, how can I even go about doing this?
I would like to complete this using approximation.
I am new to Python and have no way how to find the area under a curve given a function. If my function is for example 3x^2+2x+11, how can I even go about doing this?
I would like to complete this using approximation.
You could use SymPy to integrate for you, then you just need to plug in the endpoints. For example:
from sympy import Poly
from sympy.abc import x
f = Poly(3*x**2 + 2*x + 11) # Or `Poly((3, 2, 11), x)`
g = f.integrate()
# > Poly(x**3 + x**2 + 11*x, x, domain='QQ')
start, end = -1, 1
result = g(end) - g(start)
# > 24
I just built this which does approximations.
def integrate(f, a:float, b:float) -> float:
''' given a function, work out the integral '''
area = 0
x = a
parts = 100000
for i in range(parts):
dx = (b-a)/parts
y_0 = f(x)
y_1 = f(x+dx)
x = x+dx
height = (y_1 + y_0) /2
area = area + (height*dx)
return area
def f(x): return 3*x**3 + x**2 + 11
r = integrate(f, 0, 1)
print(r)
result for the given example:
12.08333333342187