Writing a Function in Python

Problem #1

In Problem 1, we had to write a function in order to solve the following definite integral:Screen Shot 2015-09-09 at 9.00.49 PM

In order to begin this problem, you must import the scipy package for integration.  For this reason, the first line of my code was “from scipy import integrate”.  Next, I imported the numpy package for the exponential component of this problem.  This is written as “import numpy as np” in the second line of my code.

Now we have finished importing all the packages we need to successfully solve this integral.  The next step is to define the function.  We have three variables: a, b, c. Making sure that the function integrates from 0 to 100, defining the function looks like this: Screen Shot 2015-09-09 at 9.11.05 PM

Finally, we must call the function (the third step to writing any function in python).  This is why the last line of my function reads “my_integrator(1,2,3)”.  The final solution to Homework 1 Problem 1 is shown below.

 Screen Shot 2015-09-09 at 9.15.17 PM

Problem #2

In Problem 2, we had to create a histogram.  Once again, we followed the same 3 steps to writing any function: import packages, define the function, call the function.

We first had to import the packages matplotlib (in order to see the visual for the histogram) and numpy for the random number generator.  This is why the first 3 lines of my function read:

Screen Shot 2015-09-09 at 9.25.48 PM

Now it is time to define the function.  The first part of this reads “def histogram(avg,b,n):” where avg I chose to be 5000, b (the standard deviation) I chose to be 10, and n (the number of bins) I chose to be 200.  For a first timer, I was surprised at how well the histogram looked with these numbers.  The links provided in the description of this problem were very helpful in the second step of this problem which reads: Screen Shot 2015-09-09 at 9.32.41 PM

Finally, we have to call our function using the values I mentioned above.  The final product of Problem 2 is below [Figure 1].

Screen Shot 2015-09-09 at 9.34.48 PM

Figure 1 – Histogram

Screen Shot 2015-09-09 at 9.33.42 PM

Problem 2 – final code