Loading [MathJax]/jax/element/mml/optable/MathOperators.js
Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Physics LibreTexts

28.5: Advanced topics

( \newcommand{\kernel}{\mathrm{null}\,}\)

This section introduces a few more advanced topics that allow you to use computer programming to simplifying many tasks. In this section, we will show you how you can write your own program to numerically estimate the value of an integral of any function.

Defining your own functions

Although Python provides many modules and functions, it is often useful to be able to define your own functions. For example, suppose that you would like to define a function that calculates 12x2+14x3+cos(2x), for a given value of x. This is done easily using the def keyword in Python:

python code 28.5.1

Defining a function

1#import the math module in order to use cos
2import math as m
3 
4#define our function and call it myfunction:
5def myfunction(x):
6    return x**2 / 3 + x**3 / 4 + m.cos(2*x)
7     
8#Test our function by printing out the result of evaluating it as x = 3
9print ( myfunction(3) )

Output

110.710170286650365

A few things to note about the code above:

  • Functions are defined using the def keyword followed by the name that we choose for the function (in our case, myfunction)
  • If functions take arguments, those are specified in parenthesis after the name of the function (in our case, we have one argument that we chose to call x)
  • After the name of the function and the arguments, we place a colon
  • The code that belongs to the function, after the colon, must be indented (this allows Python to know where the code for the function ends)
  • The function can “return” a value; this is done by using the return keyword.
  • We used the “operator” ** to take the power of a number (x**2), and the operator *, to multiply numbers. Python would not understand something like 2x; you need to use the multiplication operator, i.e. 2*x.

In the example above, we wrote a Python function to represent a mathematical function. However, one can write a function to execute any set of tasks, not just to apply a mathematical function. Python functions are very useful in order to avoid having to repeatedly type the same code.

Recall that the numpy module allows us to apply functions to arrays of numbers, instead of a single number. We can modify the code above slightly so that, if the argument to the function, x, is an array, the function will gracefully return an array of numbers to which the function has been applied. This is done by simply replacing the call to the math version of the cos function by using the numpy version:

python code 28.5.2

Defining a function that works on an array

01#import the numpy module in order to use cos to an array
02import numpy as np
03 
04#define our function and call it myfunction:
05def myfunction(x):
06    return x**2 / 3 +x**3 / 4 + np.cos(2*x)
07     
08 #Test our function by printing out the result and evaluating it at x = 3 (same as before)
09 print( myfunction(3) )
10  
11 #Test it with an array
12 xvals = np.array([1, 2, 3])
13 print ( myfunction(xvals) )

Output

110.710170286650365
2 
3[ 0.1671865   2.67968971   10.71017029]

where we created the array xvals using the numpy module.

Using a loop to calculate an integral

The ability to define our own functions in Python allows us to easily simplify complex tasks. Using “loops” is another way that computer programming can greatly simplify calculations that would otherwise be very tedious. In a loop, one is able to repeat the same task many times. The example below simply prints out a statement five times:

Python code 28.5.3

A simple loop

1#A loop to print out a statement 5 times:
2 
3for i in range(5):
4    print("The value of i is ", i)

Output

1The value of i is 0
2The value of i is 1
3The value of i is 2
4The value of i is 3
5The value of i is 4

A few notes on the code above:

  • The loop is defined by using the keywords for ... in
  • The value after the keyword for is the “iterator” variable and will have a different value each time that the code inside of the loop is run (in our case, we called the variable i)
  • The value after the keyword in is an array of values that the iterator will take
  • The range(N) function returns an array of N integer values between 0 and N-1 (in our case, this returns the five values 0,1,2,3,4)
  • The code to be executed at each “iteration” of the loop is preceded by a colon and indented (in the same way as the code for a function also follows a colon and is indented)

We now have all of the tools to evaluate an integral numerically. Recall that the integral of the function f(x) between xa and xb is simply a sum:

xbxaf(x)dx=limΔx0i=N1i=0f(xi)ΔxΔx=xbxaNxi=xa+iΔx

The limit of ∆x → 0 is equivalent to the limit N → ∞. Our strategy for evaluating the integral is:

  1. Define a Python function for f(x).
  2. Create an array, xvals, of N values of x between x_{a} and x_{b}.
  3. Evaluate the function for all those values and store those into an array, fvals.
  4. Loop over all of the values in the array fvals, multiply them by ∆x, and sum them together.

Let’s use Python to evaluate the integral of the function f(x) = 4x^{3}+3x^{2}+5 between x = 1 and x = 5:

Python Code \PageIndex{4}

Numerical integration of a function

01#import numpy to work with arrays:
02import numpy as np
03 
04#define our function
05def f(x):
06    return 4*x**3 + 3*x**2 + 5
07     
08#Make N and the range of integration variables:
09N - 1000
10xmin = 1
11xmax = 5
12 
13#create the array of values of x between xmin and xmax
14xvals = np.linspace(xmin, xmax, N)
15 
16#evaluate the function at all those values of x
17fvals = f(xvals)
18 
19#calculate delta x
20deltax = (xmax - xmin) / N
21 
22#initialize the sum to be zero:
23sum = 0
24 
25#loop over the values fvals and add them to the sum
26for fi in fvals:
27    sum = sum + fi*deltax
28     
29#print the result:
30print("The integral between {} and {} using {} steps is {:.2f}".format(xmin, xmax, N, sum))

Output

1The integral between 1 and 5 using 1000 steps is 768.42

One can easily integrate the above function analytically and obtain the exact result of 768. The numerical answer will approach the exact answer as we make N bigger. Of course, the power of numerical integration is to use it when the function cannot be integrated analytically.

Exercise \PageIndex{1}

What value of N should you use above in order to get within 0.01 of the exact analytic answer?

Answer


This page titled 28.5: Advanced topics is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by Ryan D. Martin, Emma Neary, Joshua Rinaldo, and Olivia Woodman via source content that was edited to the style and standards of the LibreTexts platform.

Support Center

How can we help?