#!/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") for i in range(len(xi)-1): # do each element in sequence x = np.linspace(xi[i],xi[i+1],10) # make 10 x points inside the lement fhat = points(x,xi[i],xi[i+1],np.sin(xi[i])+0.1*xi[i]+2,np.sin(xi[i+1])+0.1*xi[i+1]+2) ax.plot(x,fhat,"g-+") # plot fhat that was returned by points ax.plot([xi[i],xi[i]],[1,3.5],"k:") # add the element edges ax.plot([xi[-1],xi[-1]],[1,3.5],"k:")