import numpy as npimport matplotlib.pyplot as plt
Definition
A Riemann sum of a function $f(x)$ over a partition
$$x_0 = a < x_1 < \cdots < x_{N1} < x_N = b$$
is a sum of the form
$$\sum_{i=1}^N f(x_i^ * ) (x_i  x_{i1}) \ \ , \ x_i^* \in [x_{i1},x_i]$$
where each value $x_i^* \in [x_{i1},x_i]$ in each subinterval is arbitrary.
Riemann sums are important because they provide an easy way to approximate a definite integral
$$\int_a^b f(x) \, dx \approx \sum_{i=1}^N f(x_i^ * ) (x_i  x_{i1}) \ \ , \ x_i^* \in [x_{i1},x_i]$$
Notice that the product $f(x_i^ * ) (x_i  x_{i1})$ for each $i$ is the area of a rectangle of height $f(x_i^ * )$ and width $x_i  x_{i1}$. We can think of a Riemann sum as the area of $N$ rectangles with heights determined by the graph of $y=f(x)$.
The value $x_i^*$ chosen in each subinterval is arbitrary however there are certain obvious choices:
 A left Riemann sum is when each $x_i^* = x_{i1}$ is the left endpoint of the subinterval $[x_{i1},x_i]$
 A right Riemann sum is when each $x_i^* = x_i$ is the right endpoint of the subinterval $[x_{i1},x_i]$
 A midpoint Riemann sum is when each $x_i^* = (x_{i1} + x_i)/2$ is the midpoint of the subinterval $[x_{i1},x_i]$
Let's visualize rectangles in the left, right and midpoint Riemann sums for the function
$$f(x) = \frac{1}{1 + x^2}$$
over the interval $[0,5]$ with a partition of size $N=10$.
f = lambda x : 1/(1+x**2)a = 0; b = 5; N = 10n = 10 # Use n*N+1 points to plot the function smoothlyx = np.linspace(a,b,N+1)y = f(x)X = np.linspace(a,b,n*N+1)Y = f(X)plt.figure(figsize=(15,5))plt.subplot(1,3,1)plt.plot(X,Y,'b')x_left = x[:1] # Left endpointsy_left = y[:1]plt.plot(x_left,y_left,'b.',markersize=10)plt.bar(x_left,y_left,width=(ba)/N,alpha=0.2,align='edge',edgecolor='b')plt.title('Left Riemann Sum, N = {}'.format(N))plt.subplot(1,3,2)plt.plot(X,Y,'b')x_mid = (x[:1] + x[1:])/2 # Midpointsy_mid = f(x_mid)plt.plot(x_mid,y_mid,'b.',markersize=10)plt.bar(x_mid,y_mid,width=(ba)/N,alpha=0.2,edgecolor='b')plt.title('Midpoint Riemann Sum, N = {}'.format(N))plt.subplot(1,3,3)plt.plot(X,Y,'b')x_right = x[1:] # Left endpointsy_right = y[1:]plt.plot(x_right,y_right,'b.',markersize=10)plt.bar(x_right,y_right,width=(ba)/N,alpha=0.2,align='edge',edgecolor='b')plt.title('Right Riemann Sum, N = {}'.format(N))plt.show()
Notice that when the function $f(x)$ is decreasing on $[a,b]$ the left endpoints give an overestimate of the integral $\int_a^b f(x) dx$ and right endpoints give an underestimate. The opposite is true is when the function is increasing.
Let's compute the value of each of the Riemann sums:
dx = (ba)/Nx_left = np.linspace(a,bdx,N)x_midpoint = np.linspace(dx/2,b  dx/2,N)x_right = np.linspace(dx,b,N)print("Partition with",N,"subintervals.")left_riemann_sum = np.sum(f(x_left) * dx)print("Left Riemann Sum:",left_riemann_sum)midpoint_riemann_sum = np.sum(f(x_midpoint) * dx)print("Midpoint Riemann Sum:",midpoint_riemann_sum)right_riemann_sum = np.sum(f(x_right) * dx)print("Right Riemann Sum:",right_riemann_sum)
Partition with 10 subintervals.Left Riemann Sum: 1.613488696614725Midpoint Riemann Sum: 1.373543428316664Right Riemann Sum: 1.1327194658454942
We know the exact value
$$\int_0^5 \frac{1}{1 + x^2} dx = \arctan(5)$$
and we can compare the Riemann sums to the value
I = np.arctan(5)print(I)
1.373400766945016
print("Left Riemann Sum Error:",np.abs(left_riemann_sum  I))print("Midpoint Riemann Sum:",np.abs(midpoint_riemann_sum  I))print("Right Riemann Sum:",np.abs(right_riemann_sum  I))
Left Riemann Sum Error: 0.24008792966970915Midpoint Riemann Sum: 0.00014266137164820059Right Riemann Sum: 0.24068130109952168
Error Formulas
A Riemann sum is an approximation of a definite integral. A natural question arises: how good of an approximation is a Riemann sum?
Theorem. Let $L_N(f)$ denote the left Riemann sum
$$L_N(f) = \sum_{i=1}^N f(x_{i1} ) \Delta x$$
where $\Delta x = (ba)/N$ and $x_i = a + i \Delta x$. The error bound is
$$E_N^{L}(f) = \left \ \int_a^b f(x) \ dx  L_N(f) \ \right \leq \frac{(ba)^2}{2 N} K_1$$
where $\left \, f'(x) \, \right \leq K_1$ for all $x \in [a,b]$.
Theorem. Let $R_N(f)$ denote the right Riemann sum
$$R_N(f) = \sum_{i=1}^N f(x_{i} ) \Delta x$$
where $\Delta x = (ba)/N$ and $x_i = a + i \Delta x$. The error bound is
$$E_N^{R}(f) = \left \ \int_a^b f(x) \ dx  R_N(f) \ \right \leq \frac{(ba)^2}{2 N} K_1$$
where $\left \, f'(x) \, \right \leq K_1$ for all $x \in [a,b]$.
Theorem. Let $M_N(f)$ denote the midpoint Riemann sum
$$M_N(f) = \sum_{i=1}^N f(x_i^* ) \Delta x$$
where $\Delta x = (ba)/N$ and $x_i^* = (x_{i1} + x_i)/2$ for $x_i = a + i \Delta x$. The error bound is
$$E_N^{M}(f) = \left \ \int_a^b f(x) \ dx  M_N(f) \ \right \leq \frac{(ba)^3}{24 N^2} K_2$$
where $\left \, f''(x) \, \right \leq K_2$ for all $x \in [a,b]$.
There are several points to notice:
 Left and right Riemann sums have the same error bound which depends on the first derivative $f'(x)$.
 Midpoint Riemann sum error bound depends on the second derivative $f''(x)$.
 We expect the midpoint Riemann sum to give a better approximation as $N \to \infty$ since its error bound is inversely proportional to $N^2$ but left/right Riemann sum error bound is inversely proportional only to $N$.
Implementation
Let's write a function called riemann_sum
which takes 5 input parameters f
, a
, b
, N
and method
and returns the Riemann sum
$$\sum_{i=1}^N f(x_i^*) \Delta x$$
where $\Delta x = (ba)/N$ and $x_i = a + i\Delta x$ defines a partition with $N$ subintervals of equal length, and method
determines whether we use left endpoints, right endpoints or midpoints (with midpoints as the default method).
def riemann_sum(f,a,b,N,method='midpoint'): '''Compute the Riemann sum of f(x) over the interval [a,b]. Parameters  f : function Vectorized function of one variable a , b : numbers Endpoints of the interval [a,b] N : integer Number of subintervals of equal length in the partition of [a,b] method : string Determines the kind of Riemann sum: right : Riemann sum using right endpoints left : Riemann sum using left endpoints midpoint (default) : Riemann sum using midpoints Returns  float Approximation of the integral given by the Riemann sum. ''' dx = (b  a)/N x = np.linspace(a,b,N+1) if method == 'left': x_left = x[:1] return np.sum(f(x_left)*dx) elif method == 'right': x_right = x[1:] return np.sum(f(x_right)*dx) elif method == 'midpoint': x_mid = (x[:1] + x[1:])/2 return np.sum(f(x_mid)*dx) else: raise ValueError("Method must be 'left', 'right' or 'midpoint'.")
Let's test our function with inputs where we know exactly what the output should be. For example, we know
$$\int_0^{\pi/2} \sin(x) \, dx = 1$$
and, since $\sin(x)$ is increasing on $[0,\pi/2]$, we know that left endpoints will give an underestimate, and right endpoints will give an overestimate.
riemann_sum(np.sin,0,np.pi/2,100)
1.0000102809119054
riemann_sum(np.sin,0,np.pi/2,100,'right')
1.007833419873582
riemann_sum(np.sin,0,np.pi/2,100,'left')
0.992125456605633
We also know that $\int_0^1 x \, dx = 1/2$ and midpoint should give the result exactly for any $N$:
riemann_sum(lambda x : x,0,1,1)
0.5
Examples
Approximate Pi
Find a value $N$ which guarantees the right Riemann sum of $f(x)=\frac{4}{1 + x^2}$ over $[0,1]$ is within $10^{5}$ of the exact value
$$\int_0^1 \frac{4}{1 + x^2} dx = \pi$$
Compute
$$f'(x) = \frac{8x}{(1+x^2)^2}$$
Use brute force optimization to find a bound on $\left f'(x) \right$ on $[0,1]$:
x = np.linspace(0,1,1000)y = np.abs(8*x/(1 + x**2)**2)np.max(y)
2.5980759093919907
Therefore, $\left f'(x) \right \leq 2.6$ for $x \in [0,1]$. Use the error bound
$$\frac{(ba)^2}{2 N} K_1 \leq 10^{5} \ \Rightarrow \ \frac{1.3}{N} \leq 10^{5} \ \Rightarrow \ 130000 \leq N$$
Let's compute the right Riemann sum for $N=130000$:
approximation = riemann_sum(lambda x : 4/(1 + x**2),0,1,130000,method='right')print(approximation)
3.1415849612722386
Verify the accuracy of the approximation
np.abs(approximation  np.pi) < 10**(5)
True
Approximate ln(2)
Find a value $N$ which guarantees the midpoint Riemann sum of $f(x)=\frac{1}{x}$ over $[1,2]$ is within $10^{8}$ of the exact value
$$\int_1^2 \frac{1}{x} dx = \ln(2)$$
Compute
$$f''(x) = \frac{2}{x^3}$$
Since $f''(x)$ is decreasing for all $x>0$ we have $\left \, f''(x) \, \right \leq 2$ for all $x \in [1,2]$. Use the error bound:
$$\frac{(ba)^3}{24 N^2} K_2 \leq 10^{8} \ \Rightarrow \ \frac{1}{12 N^2} \leq 10^{8} \ \Rightarrow \frac{10^4}{\sqrt{12}} \leq N$$
10**4 / np.sqrt(12)
2886.751345948129
Therefore a partition of size $N=2887$ guarantees the desired accuracy:
approximation = riemann_sum(lambda x : 1/x,1,2,2887,method='midpoint')print(approximation)
0.6931471768105913
Verify the accuracy of the approximation:
np.abs(approximation  np.log(2)) < 10**(8)
True
Exercises
Exercise 1. Consider the integral
$$\int_1^2 \frac{dx}{1+x^3}$$
Without plotting the functions $f(x)$, $f'(x)$ or $f''(x)$, find a value $N$ such that $E_N^R(f) \leq 10^{5}$ given
$$f(x) = \frac{1}{1 + x^3} \ , \ f'(x) = \frac{3 x^{2}}{\left(x^{3} + 1\right)^{2}} \ , \ f''(x) = \frac{6 x \left(2 x^{3}  1\right)}{\left(x + 1\right)^{3} \left(x^{2}  x + 1\right)^{3}} \\$$
Exercise 2. Plot the function $f''(x)$ from the previous question on the interval $[1,2]$ and find a value $N$ such that $E_N^M(f) \leq 10^{5}$ for the integral in the previous question.
Exercise 3. Let $f(x) = x^x$ and note that
$$f'(x) = x^{x} \left(\log{\left(x \right)} + 1\right) \ , \ f''(x) = x^{x} \left(\log{\left(x \right)} + 1\right)^{2} + x^{x1}$$
Plot the function $f''(x)$ and use that information to compute $T_N(f)$ for the integral
$$\int_1^2 x^x \, dx$$
such that $E_N^T(f) \leq 10^{3}$.
FAQs
What is the formula for Riemann sum? ›
The Riemann sum formula is A = ∑ f ( x i ) Δ x , where A is the area under the curve on the interval being evaluated, f ( x i ) is the height of each rectangle (or the average of the two heights in the case of a trapezoid), and is the width of each rectangle or trapezoid.
How to do Riemann sums step by step? ›Step 1: First, we must find the width of each of the subintervals. Step 2: Next, we find the locations of the right endpoints of the rectangles using the equation x i = a + Δ x ⋅ i . Step 3: Now that we have the the width and right endpoint of each of the rectangles, we can compute the right Riemann sum.
What is Riemann sum in math? ›In mathematics, a Riemann sum is a certain kind of approximation of an integral by a finite sum. It is named after nineteenth century German mathematician Bernhard Riemann. One very common application is approximating the area of functions or lines on a graph, but also the length of curves and other approximations.
How to do mathematical operations in Python? ›For straightforward mathematical calculations in Python, you can use the builtin mathematical operators, such as addition ( + ), subtraction (  ), division ( / ), and multiplication ( * ). But more advanced operations, such as exponential, logarithmic, trigonometric, or power functions, are not built in.
How do you write a math sum in Python? ›The Python sum() function calculates the total of all numerical values in an iterable. sum() works with both integers and floatingpoint numbers. The sum() function has an optional parameter to add a number to the total. alculating the sum of a list is a common operation in Python.
What are the two types of Riemann sums? ›The three most common types of Riemann sums are left, right, and middle sums, but we can also work with a more general Riemann sum. The only difference among these sums is the location of the point at which the function is evaluated to determine the height of the rectangle whose area is being computed.
What is the difference between integral and Riemann sum? ›Definite integrals represent the exact area under a given curve, and Riemann sums are used to approximate those areas. However, if we take Riemann sums with infinite rectangles of infinitely small width (using limits), we get the exact area, i.e. the definite integral!
What is the most accurate Riemann sum? ›Riemann sums can have a left, right, middle, or trapezoidal approximations. The most accurate are usually the trapezoidal and middle rectangle approximations because they only give up a small amount of area.
Why do we use Riemann sums? ›Riemann sums are used to approximate ∫ a b f ( x ) d x by using the areas of rectangles or trapezoids for the approximating areas. Each rectangle/trapezoid has width Δx. How we choose the height of the rectangles gives us different methods of approximation, and there is also the trapezoidal method.
What type of math is the Riemann hypothesis? ›Riemann hypothesis, in number theory, hypothesis by German mathematician Bernhard Riemann concerning the location of solutions to the Riemann zeta function, which is connected to the prime number theorem and has important implications for the distribution of prime numbers.
What is the math problem the Riemann hypothesis? ›
The Riemann hypothesis, one of the last great unsolved problems in math, was first proposed in 1859 by German mathematician Bernhard Riemann. It is a supposition about prime numbers, such as two, three, five, seven, and 11, which can only be divided by one or themselves.
Can I learn to code if I'm bad at math? ›“It's absolutely not a barrier to becoming a web developer.” According to Web Developer Charlotte O'Hara, it's not only easy to learn to code without having a background in math, but outside of some routine arithmetic, most web development projects don't rely heavily on math at all.
What are the 4 operations in Python? ›Operator  Name  Example 

+  Addition  x + y 
  Subtraction  x  y 
*  Multiplication  x * y 
/  Division  x / y 
The Python package SymPy can symbolically solve equations, differential equations, linear equations, nonlinear equations, matrix problems, inequalities, Diophantine equations, and evaluate integrals.
How do you solve sums in Python? › ❮ Previous Next ❯
 ExampleGet your own Python Server. x = 5. y = 10. print(x + y) Try it Yourself »
 Example. x = input("Type a number: ") y = input("Type another number: ") sum = int(x) + int(y) print("The sum is: ", sum) Try it Yourself »
 ❮ PreviousLog in to track progress Next ❯
Python sum() Function
The sum() function returns a number, the sum of all items in an iterable.
A function is a collection of statements that you can execute wherever and whenever you want in the program. You may send variables to the function to influence what is getting computed by statements in the function, and the function may return new objects back to you.
What is the difference between a left and right Riemann sum? ›A left Riemann sum uses rectangles whose topleft vertices are on the curve. A right Riemann sum uses rectangles whose topright vertices are on the curve. The graph of the function has the region under the curve divided into 4 rectangles of equal width, touching the curve at the top left corners.
What is Xi in Riemann sum? ›Here xi∗ is the sample point in the ith subinterval. If the sample points are the midpoints of the subintervals, we call the Riemann Sum the Midpoint Rule.
How do you tell if Riemann sum is overestimate or underestimate? ›If the graph is increasing on the interval, then the leftsum is an underestimate of the actual value and the rightsum is an overestimate. If the curve is decreasing, then the rightsums are underestimates and the leftsums are overestimates.
Is Riemann sum the same as trapezoidal rule? ›
Riemann sums use rectangles, which make for some pretty sloppy approximations. But what if we used trapezoids to approximate the area under a function instead? Key idea: By using trapezoids (aka the "trapezoid rule") we can get more accurate approximations than by using rectangles (aka "Riemann sums").
Is Riemann sum the same as midpoint? ›The midpoint Riemann sum is another name for the midpoint method, also called the midpoint rule, in mathematics. It is the sum of the area of each rectangle within a given interval under the curve of a function.
What is the difference between trapezoidal and midpoint Riemann sum? ›The midpoint method uses a point in the middle of the interval to find the height of the rectangle. The trapezoid method uses a trapezoid instead of a rectangle to approximate the area of each interval. Try the following: The applet initially shows a line and a Riemann sum using 4 intervals with left endpoints.
What is the disadvantage of Riemann sum? ›The disadvantage of the notation is that, as we use it for real applications, the concept of Riemann sums often gets lost. The integrals become formulas and they get memorized but not understood. Remember: behind every (any, all) definite integral is a Riemann sum.
Why can a Riemann sum be negative? ›So, the Riemann sum is the sum of signed areas of rectangles: rectangles that lie above the axis contribute positive values, and rectangles that lie below the axis contribute negative values to the Riemann sum.
What is a trapezoidal Riemann sum? ›Trapezoidal Riemann Sum: A trapezoidal Riemann sum uses the sum of the areas of trapezoids to estimate the area under a curve.
What did Riemann do for calculus? ›He was one of the first to study differential equations involving complex variables, and his work led to a profound connection with group theory. He introduced new general methods in the study of partial differential equations and applied them to produce the first major study of shock waves.
What is the right endpoint rule? ›Rule: RightEndpoint Approximation
Figure 5.1. 3: In the rightendpoint approximation of area under a curve, the height of each rectangle is determined by the function value at the right of each subinterval.
left endpoint, the right endpoint or somewhere in the middle of the interval. Question: If the function is increasing, then the lower sum is the left sum? Answer: Correct. It's the exact opposite of the situation with an increasing function.
What is the hardest math? › Separatrix Separation. A pendulum in motion can either swing from side to side or turn in a continuous circle. ...
 Navier–Stokes. ...
 Exponents and dimensions. ...
 Impossibility theorems. ...
 Spin glass.
What is the hardest math problem? ›
x^{3}+y^{3}+z^{3}=k, with k being all the numbers from one to 100, is a Diophantine equation that's sometimes known as "summing of three cubes." When there are two or more unknowns, as is the case here, only the integers are studied.
What is the biggest math problem in the world? ›One of the greatest unsolved mysteries in math is also very easy to write. Goldbach's Conjecture is, “Every even number (greater than two) is the sum of two primes.” You check this in your head for small numbers: 18 is 13+5, and 42 is 23+19. Computers have checked the Conjecture for numbers up to some magnitude.
What is the 1 million dollar math problem? ›The first milliondollar maths puzzle is called the Riemann Hypothesis. First proposed by Bernhard Riemann in 1859 it offers valuable insights into prime numbers but it is based on an unexplored mathematical landscape. If you can show that its mathematical path will always lie true, $1m (£600,000) is all yours.
What are the 7 math millennium problems? ›Clay “to increase and disseminate mathematical knowledge.” The seven problems, which were announced in 2000, are the Riemann hypothesis, P versus NP problem, Birch and SwinnertonDyer conjecture, Hodge conjecture, NavierStokes equation, YangMills theory, and Poincaré conjecture.
What is the hardest math problem the Riemann hypothesis? ›In mathematics, the Riemann hypothesis is the conjecture that the Riemann zeta function has its zeros only at the negative even integers and complex numbers with real part 12. Many consider it to be the most important unsolved problem in pure mathematics.
Is right Riemann sum an overestimate? ›If is increasing on the interval , a left Riemann sum underestimates, and a right Riemann sum overestimates the integral over the interval.
What is the second fundamental theorem of calculus? ›The Second Fundamental Theorem of Calculus is the formal, more general statement of the preceding fact: if f is a continuous function and c is any constant, then A(x)=∫xcf(t)dt is the unique antiderivative of f that satisfies A(c)=0.
Can a Riemann integral be infinity? ›In order to take a Riemann integral, you need to divide the domain up into a finite number of finitelength pieces, which is impossible to do if the domain has infinite length.
How to do sum of digits coding in Python? ›Using Sum() method
The sum() method is used to compute the sum of digits of a number in python in a list. Convert the number to a string using str(), then strip the string and convert it to a list of numbers with the strip() and map() methods, respectively. Then, compute the total using the sum() method.
 def twosum(nums, target):
 length = len(nums)
 for i in range(length):
 for j in range(i + 1, length):
 if nums[i] + nums[j] == target:
 return [i, j]

 n = [3, 1, 1, 2]
How do you solve polynomial equations in Python? ›
 Import the math module.
 Take in the coefficients of the polynomial equation and store it in a list.
 Take in the value of x.
 Use a for loop and while loop to compute the value of the polynomial expression for the first three terms and store it in a sum variable.
The Python += operator lets you add two values together and assign the resultant value to a variable. This operator is often referred to as the addition assignment operator. It is shorter than adding two numbers together and then assigning the resulting value using both a + and an = sign separately.
How does += work in Python? ›+= adds a number to a variable, changing the variable itself in the process (whereas + would not). Similar to this, there are the following that also modifies the variable: = , subtracts a value from variable, setting the variable to the result. *= , multiplies the variable and a value, making the outcome the variable.
How do you sum a number in Python using functions? ›You can now use Python's builtin function sum() to add multiple numeric values together. This function provides an efficient, readable, and Pythonic way to solve summation problems in your code. If you're dealing with math computations that require summing numeric values, then sum() can be your lifesaver.
How do you sum a two digit number in Python? ›for i in range(5): add = 0 num = input("Number: ") num = int(num) if num > 9 and num < 100: num = str(num) add = int(num[0]) + int(num[1]) print("The addition of the two digits is: " + str(add)) else: print("It is not a two digit number.
How do you find the sum of two numbers in coding? ›printf("Enter two integers: "); scanf("%d %d", &number1, &number2); Then, these two numbers are added using the + operator, and the result is stored in the sum variable. Finally, the printf() function is used to display the sum of numbers. printf("%d + %d = %d", number1, number2, sum);
How do you sum two elements in an array in Python? ›STEP 1: Declare and initialize an array. STEP 2: The variable sum will be used to calculate the sum of the elements. Initialize it to 0. STEP 3: Loop through the array and add each element of the array to the variable sum as sum = sum + arr[i].
What is two sum in Python? ›The Two Sum Problem
Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target . You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Sympy is a package for symbolic solutions in Python that can be used to solve systems of equations.
Does Python have an equation solver? ›The Python package SymPy can symbolically solve equations, differential equations, linear equations, nonlinear equations, matrix problems, inequalities, Diophantine equations, and evaluate integrals.
What program solves system of equations in Python? ›
To solve a linear matrix equation, use the numpy. linalg. solve() method in Python. The method computes the “exact” solution, x, of the welldetermined, i.e., full rank, linear matrix equation ax = b.