GEOL 5470
Homework/Labwork Humphrey
If you need to reuse code, it is often useful to bundle it into a function that you can name and then reuse in your code. In addition, many numpy methods need to be passed not just some variables, but a way of generating variables. A good example of this is a method to integrate a curve. Typically you have to pass to the integration method a block of code that will generate the entire curve. The way to do this is to write a function, and pass the name of the function to the integration method.
We are going to write a somewhat trivial function to differentiate a curve. This function will take as input the x and y values of the curve as arrays, and will return the derivative as plot-able x and y arrays. The syntax of a python function is a little like that of a for loop. Instead of ‘for’ it starts with the keyword ‘def’, has an argument list enclosed in ‘()’. The ‘def’ line ends in a ‘:’, and the actual function code is indented and ends in a ‘return’ statement that sends the named variables back to the main program.
def mydiff(xin,yin):
# some lines of indented code that produce the ‘diff’ array and an ‘xout’ array of appropriate x positions
return xout,diff
The way it is used in your code is that the function definition is placed early in your code, typically just after the ‘imports’. Then when you want to find the derivative of an array, such as the derivative of the array w, which is spaced evenly on that x-axis at points x, you have a line of code saying something like x2,y2 = mydiff(x,w), where x2 and y2 are the x-locations and the derivative values.
Several comments. When you ‘call’ your function ( as in x2,y2 = mydiff(x,w) ) the variable names ‘x,w’ are called arguments, and since our function returns 2 arrays, we assign them to the variables x2,y2 (which are created by the assignment). Inside the function, the function itself has a separate set of variable names, which is separate to and unknown by the main program (that is one of the main reasons for having stand-alone functions!). So inside the function, the input arguments, and the output variables will have different names(!) from the main program. This is explained in the example function code on the web pages.
Your job - Modify your sine/cosine program (make sure you save your old programs) to use a ‘function’ to differentiate instead of a for loop.
Note, your function is very primitive, it should really have error checking and be able to handle non-evenly spaced data etc. However, you should compare your results by also plotting the results of the numpy.diff() method. A really nice thing to add to function definitions is a ‘doc-string’, which is a triple quoted string, placed as the first line(s) after the ‘def’ line, which comments on what the function does, and what its input and output needs to be.