Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – numerical integration with NumPy


We'll repeat the calculation from the previous example with NumPy. Execute the following code and see what happens:

import numpy as np
def func(x):
    return np.exp(x) * np.cos(x)

a=0; b=8
dx = 0.1

for i in range(4):
    x = np.arange(a, b + dx, dx)
    f = func(x)

    print("dx = {0}  integral = {1}".format(dx, np.trapz(f,x)))
    dx = dx / 10

The output is shown in the following screenshot:

What just happened?

We defined a Python function that represents the mathematical function used in the previous example. We then used a for loop to numerically integrate the function with trapz, using different spacing of the independent variable x. The first argument to trapz is a NumPy array that contains the values of the function to be integrated. The x values can be specified as either an array of values (which do not have to be uniformly spaced) or a single scalar value dx that defines the spacing between points. If the array containing the...