Skip to content

Instantly share code, notes, and snippets.

@piyush01123
Created April 23, 2020 05:32
Show Gist options
  • Save piyush01123/00ff005ae205c29eabab063aa50088fe to your computer and use it in GitHub Desktop.
Save piyush01123/00ff005ae205c29eabab063aa50088fe to your computer and use it in GitHub Desktop.
Definite integral as sum
import numpy as np
def integrate(f,start,end,dx=.001):
x_points = np.arange(start,end,dx)
y_points = [f(x) for x in x_points]
area = dx*(sum(y_points[1:-1])+0.5*(y_points[0]+y_points[-1]))
# area = dx*sum(y_points)
return area
def main():
a1 = integrate(np.sin, 0, np.pi)
a2 = integrate(lambda x: np.sqrt(1-x**2), -1, 1)
a3 = integrate(lambda x: x**2,0,1)
test = lambda a, b: np.isclose(a,b,atol=.001)
print(test(a1,2), test(a2, np.pi/2), test(a3,1/3))
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment