Part 2/3 of my kata series. [Part 1](http://www.codewars.com/kata/riemann-sums-i-left-side-rule)

The description changes little in this second part. Here we simply want to improve our approximation of the integral by using trapezoids instead of rectangles. The left/right side rules have a serious bias and the trapezoidal rules averages those approximations! The same assumptions exist but are pasted here for convenience.

- f will always take a single float argument 
- f will always be a "nice" function, don't worry about NaN
- n will always be a natural number (0, N] 
- b > a 
- and n will be chosen appropriately given the length of [a, b] (as in I will not have step sizes smaller than machine epsilon)
- *!!! round answers to the nearest hundredth!!!*

Source: codewars | Difficulty: EASY
Tags: Fundamentals

Mathematics

Starter code: def riemann_trapezoidal(f, n, a, b):
	

Solutions:
def riemann_trapezoidal(f, n, a, b):
	dx = (b - a) / n
	return round(dx * sum(((f(a + i * dx) + f(a + (i + 1) * dx)) / 2 for i in range(n))), 2)


def riemann_trapezoidal(f, n, a, b):
	delta_x = (b - a) / float(n)
	middle_height = lambda i: (f(a + i * delta_x) + f(a + (1 + i) * delta_x)) / 2
	arr = map(middle_height, xrange(n))
	return round(sum(arr) * delta_x, 2)


def riemann_trapezoidal(f, n, a, b):
	d = (b - a) / n
	total = 0
	for i in range(n):
		hl = f(a + d * i)
		hr = f(a + d * (i + 1))
		total += d * hl + d * (hr - hl) / 2
	return round(total, 2)


def riemann_trapezoidal(f, n, a, b):
	area = 0
	dt = (b - a) / n
	x1 = a
	for i in range(n):
		A1 = f(x1) * dt
		x1 = x1 + dt
		A2 = f(x1) * dt
		area += (A1 + A2) / 2
	return round(area + 0.001, 2)


def riemann_trapezoidal(f, n, a, b):
	dx = (b - a) / n
	y = sum((f(a + i * dx) / (2 if i in [0, n] else 1) for i in range(n + 1)))
	return round(y * dx, 2)


def riemann_trapezoidal(f, n, a, b):
	s = 0
	d = (b - a) / n
	for i in range(n):
		x = a + i * d
		y = x + d
		s += (f(x) + f(y)) * d / 2
	return round(s, 2)


def riemann_trapezoidal(f, n, a, b):
	d = (b - a) / n
	sum = f(a) + f(b)
	for i in range(1, n):
		sum += 2 * f(a + i * d)
	return round(0.5 * sum * d, 2)


def riemann_trapezoidal(f, n, a, b):
	ret = 0.5 * (f(b) + f(a))
	h = (b - a) / n
	for i in range(1, n):
		ret += f(a + i * h)
	ret = (ret * h * 100 + 0.5) // 1 / 100
	return ret