#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 19 15:40:37 2021 Plot intermediate points in a linear 'fhat' approximation to 'f' @author: neil """ import numpy as np import matplotlib.pyplot as plt def points(x,x0,x1,a0,a1): # function to return the line or a point within an element # x is a point or list of points, x0,x1, are the edges of the element, a0,a1 are the # values of the 'f' function at the element edges temp = (x - x0)/(x1 - x0) # note that x can be a list of numbers return a0*(1-temp) + a1*temp # can return a list, if x is a list xi = [0.5,1.5,4,5.5,7] # list of element boundaries xpoints = np.linspace(xi[0],xi[-1],100) # for plotting, make a list of points f = np.sin(xpoints) + 0.1*xpoints + 2 # this is the 'f' function we are approximating fig = plt.figure() # plot the 'f' function in red, leave the axis to plot 'fhat' ax = fig.add_subplot(111) #ax.plot(xpoints,f,"r-*") # ax.set_ylabel("f(x) or fhat(x)") ax.set_title("element by element fhat or f") ao = np.sin(xi[0])+0.1*xi[0]+2 n=10 for i in range(len(xi)-1): # do each element in sequence x = np.linspace(xi[i],xi[i+1],n) # make 10 x points inside the lement f = np.sin(x) + 0.1*x + 2 # produce the f curve inside the element s = 0 t = 0 for j in range(0,n): s += (f[j]*(xi[i+1]-xi[i]) - ao*(xi[i+1]-x[j])) t += x[j]-xi[i] a1 = s/(t) fhat = points(x,xi[i],xi[i+1],ao,a1) ax.plot(x,fhat,"g-+") # plot fhat that was returned by points ax.plot(x,f,"r-*") # ax.plot([xi[i],xi[i]],[1,3.5],"k:") # add the element edges ao = a1 ax.plot([xi[-1],xi[-1]],[1,3.5],"k:")