Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 34
def trapets(f, a, b, n): h = (b - a) / n return h / 2 * (f(x=a) + 2 * sum([f(x=a + i * h) for i in range(1, n)]) + f(x=b)) def simpson(f, a, b, n): h = (b - a) / n return h / 3 * (f(x=a) + 2 * sum([(i % 2 + 1) * f(x=a + i * h) for i in range(1, n)]) + f(x=b)) def TvsS(f, a, b, ns): print("{} \t{} \t{} \t{}".format("n", "trapets", "simpson", "integrate")) accurate = integrate(f, (x, a, b)) for n in ns: print("{} \t{} \t{} \t{}".format(n, float(trapets(f, a, b, n)), float(simpson(f, a, b, n)), float(accurate))) #TvsS(1-x^2, 0, 1, [2, 4, 16, 256]) #TvsS(sqrt(1+x^2), 0, 1, [2, 4, 16, 256]) print(simpson(2*x^2+2, 0, 5, 4))
280/3