integral - Integration with Riemann Sum Python -
i have been trying solve integration riemann sum. function has 3 arguments a,b,d lower limit b higher limit , d part a +(n-1)*d < b
. code far but. output 28.652667999999572
should 28.666650000000388
. if input b lower has calculate have solved problem already.
def integral(a, b, d): if > b: a,b = b,a delta_x = float((b-a)/1000) j = abs((b-a)/delta_x) = int(j) n = s = 0 x = while n < i: delta_a = (x**2+3*x+4) * delta_x x += delta_x s += delta_a n += 1 return abs(s) print(integral(1,3,0.01))
there no fault here, neither algorithm nor code (or python). riemann sum approximation of integral , per se not "exact". approximate area of (small) stripe of width dx, between x , x+dx, , f(x) area of rectangle of same width , height of f(x) it's left upper corner. if function changes it's value when go x x+dx area of rectangle deviates true integral.
have noticed, can make approximation closer making thinner , thinner slices, @ cost of more computational effort , time. in example, function f(x) = x^2 + 3*x + 4, , it's exact integral on x in [1.0,3.0) 28 2/3 or 28.66666...
the approximation rectangles crude one, cannot change that. change time takes code evaluate, say, 10^8 steps instead of 10^3. @ code:
def riemann(a, b, dx): if > b: a,b = b,a # dx = (b-a)/n n = int((b - a) / dx) s = 0.0 x = in xrange(n): f_i = (x + 3.0) * x + 4.0 s += f_i x += dx return s * dx
here, i've used 3 tricks speedup, , 1 greater precision. first, if write loop , know number of repetions in advance use for-loop instead of while-loop. it's faster. (btw, loop variables conventionally i
, j
, k
... whereas limit or final value n
). secondly, using xrange
instead of range
faster users of python 2.x. thirdly, factorize polynoms when calculating them often. should see code mean here. way, result numerically stable. last trick: operations within loop not depend on loop variable can extracted , applied after loop has ended. here, final multiplication dx.
Comments
Post a Comment