1

I have to change a script in Python that calculate the integrate of a function using the sums of Riemann with the lefthand rule and modified it so that it uses the sums of Riemann with the midpoint rule. This is the original script (lefthand rule):

import numpy as nt
import matplotlib.pyplot as plt

def func(x):
    return 1+nt.exp(-x)*nt.sin(5*x)


def Riemann(x0,xn,N):        
    x=nt.zeros((N))
    y=nt.zeros((N))
    dx=(xn-x0)/(N-1)  
    x[0]=x0
    y[0]=func(x[0])
    somme=0.0
    plt.plot([x[0],x[0]],[0,func(x[0])],'-b')    
    for i in nt.arange(1,N):
        somme=somme+y[i-1]*dx
        x[i]=x[i-1]+dx
        y[i]=func(x[i])
        plt.plot([x[i-1],x[i],x[i]],[y[i-1],y[i-1],y[i]],'-k') 
        plt.plot([x[i],x[i]],[0,y[i]],'-g')                

    plt.plot([x[N-1],x[N-1]],[0,func(x[N-1])],'-b')    
    plt.plot(x,func(x),'r')                            
    yy=nt.zeros((N))
    plt.plot(x,yy,'b')                                
    plt.title('Sums of Riemann with lefthand rule')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()

In this case, there is no error and the graphic look like this: enter image description here

Then I try to modify the script so that it uses the midpoints rule and it looks like this:


import numpy as nt
import matplotlib.pyplot as plt

def func(x):
    return 1+nt.exp(-x)*nt.sin(5*x)
    
def Riemann(x0,xn,N):        
    x=nt.zeros((N))
    y=nt.zeros((N))
    dx=(xn-x0)/(N-1)  
    x[0]=x0
    y[0]=func(x[0])
    somme=0.0
    plt.plot([x[0],x[0]],[0,func(x[0])],'-b')    
    for i in nt.arange(1,N):
        somme=somme+2*((y[i-1]+y[i])/2)*dx
        x[i]=x[i-1]+dx
        y[i]=func(x[i])
        plt.plot([x[i-1],x[i-1],x[i]],[y[i-1],((y[i-1]+y[i])/2),((y[i-1]+y[i])/2)],'-k') 
        plt.plot([x[i],x[i]],[0,y[i]],'-g')                

    plt.plot([x[N-1],x[N-1]],[0,func(x[N-1])],'-b')    
    plt.plot(x,func(x),'r')                            
    yy=nt.zeros((N))
    plt.plot(x,yy,'b')                                
    plt.title('Riemann sums with midpoints rule')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()

The graphic looks like this: enter image description here

I have two questions. First of all, what is wrong with the script for the midpoints graphic because the black lines over the red one are not supposed to stop? Secondly, is the "for" loop in the second script using the midpoints rule correctly? I cannot tell if the loop uses the midpoint rule correctly because I do not understand the rule really well. Thanks you very much and be easy because I am very new at programming.

DaveL17
  • 1,673
  • 7
  • 24
  • 38

0 Answers0