## Section3Computing Integrals with Sage ($$\int$$)

View Source

Sage can compute definite integrals. The output contains the approximate numerical value of the definite integral, followed by an upper bound of the error in the approximation.

numerical_integral(sin(x)^2, (0, 2))


Given the Fundamental Theorem, we would find the antiderivative useful.

integral(sin(x)^2, x)


The same command can be used to employ the antiderivative in the application of the Fundamental Theorem. Notice that the answer is exact and any further manipulation is likely to be simply producing a numerical approximation.

integral(sin(x)^2, (x, 0, 2))


There are integrals you really do not want to evaluate, or you do not want your reader to evaluate. A Sage cell can be configured for display purposes only—you can look but you cannot touch.

integral(e^(x^2), x)


You can give a Sage element a doctest attribute, whose value mirrors the optional hash tags used in Sage doctests. Possible values are random, long time, not implemented, not tested, known bug, absolute, relative, and optional. The values absolute and relative refer to floating-point tolerances for equality and require a second attribute tolerance to specify a floating point value. The value optional refers to the test requiring that an optional Sage package be present. The name of that package should be provided in the package attribute.

The next cell is marked in the source as doctest="random", and so is specified as unpredictable and not tested. But there is some “sample” output which will appear in the version (and always be the same).

random()


While the next cell is random, the returned value will never be more than $$0.01$$ away from $$12\text{,}$$ since the random() function stays between $$0$$ and $$1\text{.}$$ So we provide $$12.005$$ as the expected answer, but test with an absolute tolerance of $$\epsilon=0.006\text{.}$$

12 + 0.01*random()


Sage has some functions which affect output, generally making mathematics look more like mathematics via syntax. This is a simple test, and you should see the variable and superscript in italics, properly formatted as output when viewed within HTML output. We have provided expected output for doctesting, but it is sort of silly to have this as part of output, even if it is instructive.

pretty_print(html("$a^2$"))


Sage, and by extension, the Sage Cell Server, can interpret several languages. The next example has code in the R language, a popular open source language for statistics. As an author, you add the attribute language="r" to your sage element. (The default language is Sage, so you do not need to indicate that repeatedly.) Note that a language like R likes to use a “less than” character, <, special character in XML. You need to escape it by writing &lt; as we have done in the source for this example. (See the discussion in Subsection 8.1.)

As a reader you learn that the “Evaluate” button for a pre-loaded Sage cell will indicate the language in use.

ruth <- c(22, 25, 34, 35, 41, 41, 46, 46, 46, 47, 49, 54, 54, 59, 60)
bonds <- c(16, 25, 24, 19, 33, 25, 34, 46, 37, 33, 42, 40, 37, 34, 49, 73, 46, 45, 45, 5, 26, 28)
dimaggio <- c(12, 14, 20, 21, 25, 29, 30, 30, 31, 32, 32, 39, 46)
summary(ruth)
summary(bonds)
summary(dimaggio)
boxplot(ruth, bonds, dimaggio)


The Sage Cell Server supports the following languages: sage, gap, gp, html, maxima, octave, python, r, and singular.

Here is another R cell. Unfortunately, it seems Sage's doctest facility cannot be used easily with code from other languages. In the source for this example, we have employed the XML escape sequence, &lt; several times (see Subsection 8.1).

age <- c(25, 30, 56)
gender <- c("male", "female", "male")
weight <- c(160, 110, 220)
mydata <- data.frame(age,gender,weight)
summary(mydata)
cor(mydata$age,mydata$weight)
mean(mydata$age) sd(mydata$age)
plot(mydata$age,mydata$weight)


The Sage Cell server importants a few important R packages. As of 2022-06-04 these are deSolve, ggplot2, pracma, survey, swirl, and tidyverse. This next example uses the ggplot library for both a data set and the plotting capabilities. Note the initial use of the library() function. This is a modified version of the “Bubble plot” example at Top 50 ggplot2Visualizations —The Master List 1 .

# load package and data
library(ggplot2)
data(mpg, package="ggplot2")
mpg_select <- mpg[mpg\$manufacturer %in% c("audi", "ford", "honda", "hyundai"), ]
# Scatterplot
g <- ggplot(mpg_select, aes(displ, cty)) +
labs(subtitle="mpg: Displacement vs City Mileage",
title="Bubble chart")
g + geom_jitter(aes(col=manufacturer, size=hwy)) +
geom_smooth(aes(col=manufacturer), method="lm", se=F)


Here is a blank Sage cell that you may use for practice and experimentation with the commands above. Note that this cell allows a choice of languages, and is not linked with any of the previous cells, so a reader would need to start fresh, or cut/paste definitioons from other cells.

# Practice area (not linked for Sage Cell use)


On the other hand a <sage> element with no content will also create an empty Sage cell for the reader's use, but now it will be specific to a particular language and linked to others of the same language. Run the R cell above that defines the variable ruth and then try typing summary(ruth) in the cell below.

You can make Sage blocks which are of type="invisible", which will never be shown to a reader, but which get doctested. Why do this? If some code produces an error, and you hope it is fixed someday, use an invisible block to raise the error. Once fixed, the doctest will fail, and you can adjust your commentary to suit. There is such a block right now, but you will need to go to the source to see it.

Our maximum width for text, designed for readability, suggests you should format your Sage code with a maximum of about 54 characters. On a mobile device, the number of displayed characters might be as low as 28 in portrait orientation, and again around 50 in landscape. You can use a variety of techniques to shorten long lines, such as using intermediate variables. Since Sage is just a huge Python library, you can use any of Python's facilities for handling long lines. These include a continuation character (which I try to avoid using) or natural places where you can break long lines, such as between entries of a list. Also, if writing loops or functions, you may wish to have your indentation be only two characters wide (rather than, say, four).

Sage output can sometimes be quite long, though this has improved with some changes in Sage's output routines. Output code should be included primarily for doctesting purposes, and in this use, you may break at almost whitespace character and the doctesting framework will adjust accordingly. You may wish to show sample output in a static format, like a PDF, so you can consider formatting your output to fit the width constraints of that medium. Or you may even adjust exactly what is output, to keep it from being too verbose. Sage doctesting also allows for a wild-card style syntax which allows you to skip over huge chunks of meaningless or unpredictable output, such as tracebacks on error messages.

This paragraph is just a placeholder. It has handful of index entries, all starting with the letters “gas”, taken from Indexing for Editors and Authors: A Practical Guide to Understanding Indexes by Leise, Mertes, and Badgett. The intent is to test letter-by-letter versus word-by-word sorting of index entries. We use a word-by-word order, resulting in:

1. gas

3. gas production

4. gas works

5. gasoline

6. gastritis

### Titled Sage Cells.

integral(sin(x)^2, x)


You can place Sage cells inside of a paragraphs if you want to give them a title, but no numbers, etc. Their surrounding box sometimes gets clobbered in output if they are the first piece of content, so we test that here also. A defensive \leavevmode solves the problem.

r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html