'How can I optimise this?
I wrote a little algorithm that uses the Trapezium Rule to find an estimation for area under the curve between two points, but it doesn’t run the absolute fastest, how can I optimise it? It’s in python (I know python is a slow language but I just want python optimisations).
start = -2
end = 0
num = 1000
eq = lambda x: x*(x**2 -4)
h = (end - start)/num
a = start - h
ran = []
while a < end:
a += h
ran.append(round(a, 5))
values = [abs(eq(i)) for i in ran]
final = 0.5 * h * (values[0] + values[-1] + 2*sum(values[1:-1]))
print(final)
Solution 1:[1]
Using numpy, it's over 60 times faster on my machine:
start = -2
end = 0
num = 1000
eq = lambda x: x*(x**2 -4)
h = (end - start)/num
ran = np.arange(start - h, end, h)
values = eq(ran)
return 0.5 * h * (values[0] + values[-1] + 2*np.sum(values[1:-1]))
There's no reason to do it "manually" like this though – numpy.trapz has you covered.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas |
