-1

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.

D.L
  • 4,339
  • 5
  • 22
  • 45
  • `scipy` has an `integrate` module. You need to specify starting and ending points, just as you would on paper. https://docs.scipy.org/doc/scipy/tutorial/integrate.html – Tim Roberts Oct 04 '22 at 19:48
  • 1
    Or, you can just find the integral in your head (`x^3 + x^2 + 11x`) and plug in your start and end values... – Tim Roberts Oct 04 '22 at 19:53

2 Answers2

1

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • P.S. It's been a long time since I took calculus and I'm not very well versed on SymPy, so if I'm missing anything, please LMK. – wjandrea Oct 04 '22 at 20:35
  • Im sorry but im having to use approximation and not actual calculus for some reason lol – Joe Joplin Oct 04 '22 at 22:12
  • @JoeJoplin Ah, you should have said that. I think Tim's comment about SciPy will help you out then. – wjandrea Oct 04 '22 at 22:34
1

I just built this which does approximations.

  • The integrate function takes a function as its first argument.
  • requires upper and lower bounds
  • works out the rectangle areas
  • adds them together

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
D.L
  • 4,339
  • 5
  • 22
  • 45
  • Good example of the [trapezoidal rule](https://en.wikipedia.org/wiki/Trapezoidal_rule). This is one of the more popular techniques for [numerical integration](https://en.wikipedia.org/wiki/Numerical_integration). Another popular method is the [midpoint rule](https://en.wikipedia.org/wiki/Riemann_sum#Midpoint_rule) – bfris Oct 05 '22 at 00:17
  • as long as function is continuous and parts is large (dx is small), they will be good... – D.L Oct 05 '22 at 09:09