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


Let's start by using Sage functions to numerically integrate a symbolic function of one variable:

var('x')
f(x) = e^x * cos(x)
f.show()

a = 0
b = 8
p = plot(f, (x, a, b))
p.show(figsize=(4, 3))

print("Integral of f(x) from {0} to {1}:".format(a,b))
print("  Analytical definite integral: {0}"
    .format(f.integral(x, a, b).n()))

integral_value, tolerance, num_evals, error_code = \
    f.nintegral(x, a, b)
    
print("  Using nintegral: {0}".format(integral_value))
# also nintegrate

integral_value, tolerance = numerical_integral(f, a, b)
print("  Using numerical_integral: {0}".format(integral_value))

A plot of the function, along with the integration results, is shown below:

What just happened?

We defined a symbolic function f(x) and defined an interval on which to compute the definite integral. As a point of reference, we used the symbolic integration method integral with limits to compute the definite integral symbolically. We used the method n...