<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 25 09:52:03 2021

@author: conda
"""

from numpy import eye, zeros, linspace, pi, sin
from matplotlib.pyplot import plot, show, legend

def finiteDifferenceForLoops( N, h ):
    # create N x N matrix filled with zeros
    A = zeros((N,N))
    
    # set first and last row to unit row
    A[0,0] = 1.0
    A[N-1,N-1] = 1.0
    for i in range(1,N-1):
        A[i,i] = -2.
        A[i, i-1] = 1.
        A[i, i+1] = 1.
        
    # scale with 1/(h**2) with h = L/N    
    A *= 1./h**2 
    return A  

def finiteDifferenceEye(N, h):
    # create tridiagonal matrix using numpy's eye
    A = -2.*eye(N) + eye(N, k=-1) + eye(N, k=1)
    
    # manipulate first and last row to accommodate boundary data
    A[0,:] = 0.
    A[N-1,:] = 0.
    A[0,0] = 1.
    A[N-1,N-1] = 1.
    
    # scale with 1/h**2     
    A *= 1./h**2 
    return A

########################################
## main part
########################################

N = 500    
x=linspace(0,2*pi,N)

# A = finiteDifferenceForLoops(N, h=2.*pi/N)
A = finiteDifferenceEye(N, h=2.*pi/N)

# compute sin(x) for all values of vector x
u = sin(x)
# NOTE: we have to set the first and last entry in u
# because there the finite difference approximation 
# is not valid. At this point sin is zero so we are lucky.
u = sin(x)
du = A @ u 

plot(x,u, label='sin(x)')
plot(x,du, label = 'D^2 sin (x)')
legend(loc='upper right')
# show plots
show()
</pre></body></html>