# -*- coding: utf-8 -*- """ @author: neil """ # program to plot a sine curve and its derivative (cosine) # the cosine is calculated simply as the slope of the sine curve by # taking (sine(x+dx)-sine(x))/((x+dx)-x) as dy/dx # the main reason for this program is to illustrate simple python coding, introduce 'numpy' # and show a standard way of plotting on the screen using 'matplotlib' import numpy as np import matplotlib.pyplot as plt # start of program, note that comments are GOOD!, also note that numbers are hard coded in this program which # is poor programing, all numbers should be defined at the beginning of a program in a header section so they can be changed x = np.linspace(0,7,30) #np.linspace(start,stop,number) is a very useful generator, look it up! (google 'numpy linspace') w = np.sin(x) # create a list of x points and the matching sin(x) points, in w, note np.sin() works on entire array fig = plt.figure() #create a place to plot. plt.figure() is a standard method of matplotlib to make a blank plotting canvas ax = fig.add_subplot(111) #create 1 axes. you can create multiple plots on the same figure with subplot(2,3,1) example ax.plot(x,w,'r-o') #simple 'xy' plot, with sine 'w' ploted against radians 'x', you can add LOTS of options # very common is a string like 'r-o' for a red 'r', line '-', with markers 'o' ax.set_title("Sine and Derivative") ax.set_xlabel("This is an x label, Radians") ax.set_ylabel("Blue is the numpy cosine, black is ours") diff = np.zeros(len(w)-1) # many ways to make an array, using np.zeros(shape and size) makes a zero filled array for i in np.arange(0,len(w)-1): # 'for' loop, remember it always has a ':' to denote the following is part of the loop diff[i] = w[i+1] - w[i] # calc the difference between all the adjacent values of the sine curve diff = diff/(x[1]-x[0]) # divide the difference by 'dx' and we have an estimate of 'dy/dx' ax.plot(x[:-1],diff,'k-+') # note the x positions are not correct, they should be in the middle of the steps # also the x[:-1]; is pythonic 'slicing' for 'part of array x, starting at 0 excluding the last ax.plot(x,np.cos(x),'b') # might as well plot the cosine, or the analytic derivative plt.show() # Spyder will let you skip this line, but it is required for a standalone program