How to Interpolate a Function at a Point using Lagrange Polynomials

The Lagrange polynomials are used to find the value of a function at a point when we know its values at some other points. Let us see how to interpolate a function at a point this way.

  • First we need to read the values of the points x1, x2, ... ,xn and the values of the function at these points, i.e. y1, y2, ... , yn. We read them from an input file in two columns and set a counter to count each set x(i),y(i), where i=1,n. Optionally, we may display the input on the screen. It is always a good practice to do so.
  • Next, we read xx, the point at which we wish to interpolate the function. This has been named so to avoid confusion with the array, x.
  • We set the value of P=0 and initiate a loop from 1 to n. In the loop, we will calculate P. Here we also set L=1. Note that P is a summation term, so it is set to 0. Whereas, L is a result of multiplication, so it is set to 1.
  • We create another loop for calculating L for each i. L will be reset to 1 everytime it exits this loop. All the boxed terms in the illustration are calculated here.
  • Finally, we display the result after the final value of P has been calculated.
  • Optional:  You may choose to begin the array from x=0. For this you must mention x(0:n) instead of x(100) used in the program. Additionally, you will have to change all the loops to the form do i=0, count-1.
Let us understand this better through an illustration.

The Lagrange Polynomial for Calculating the Value of a function at x (named xx in the program). The j loop has been shown in red to avoid confusion with the i loop. Each L is shown in a box.
Now for the Fortran program,

!To interpolate a point using Lagrange Polynomials
program Lagrange
    implicit none
    real P,L,xx,s,x(100),y(100),num,den
    integer i,j,n,count
   
    n=100
    open (unit=5,file='lagrange.dat') !To read data from file
 

    count=0
    do i=1,n
          read (5,*, end= 10) x(i),y(i)
          count=count+1
    end do

    10 write (*,*)
    write (*,*) "Data provided for ",count," points"
    write (*,20) "x(i)","f(x(i))=y(i)"
    20 format (7x,a4,10x,a12)
     
    do i=1,count
        write(*,*) x(i),y(i)
    end do

      write (*,*) "Give the point at which you want to interpolate the function"
    read (*,*) xx
    write (*,*) "Interpolating the value of the point", xx,"using the given data"

    !To calculate the value of the polynomial
     P=0.0
       
    do i=1,count
        L=1
        do j=1,count
              if (i.eq.j) cycle
            num=(xx-x(j))
            den=(x(i)-x(j))
            s=num/den
            L=L*s
           end do
        P=P+(L*y(i))
    end do

    write (*,*) "The value of the function at ",xx," is ",P
    write (*,*)"i.e. f(",xx,")=",P
           
end program Lagrange
   

Sample Output for Interpolation using Lagrange Polynomials

No comments:

Post a Comment