Introducción a Wolfram Mathematica
Introducción a Wolfram Mathematica
Ana Martı́n-Caraballo
Eva Barrena Algara
1
© BY-NC: No está permitido reproducir el contenido de este documento sin citar la proce-
dencia. No está permitido obtener beneficios comerciales de la distribución del contenido de este
documento o de sus derivados.
Contents
1.1 Introducción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
II
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
III
2.4 Crecimiento, decrecimiento, concavidad y convexidad . . . . . . . . . . . . . 29
2.5 Integración . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.2 Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.5 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
IV
3.1 Funciones: Definición y representación gráfica . . . . . . . . . . . . . . . . . 50
V
3.5 Representing regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
VI
Tema 1. Elementos básicos del
Álgebra Lineal
1.1 Introducción
El programa Mathematica ofrece opciones variadas para trabajar, como pueden ser,
entre otras:
1
1.2 Introducción a Mathematica
Como se indicó anteriormente, un cuaderno se divide en celdas que pueden ser de varios
tipos (comandos, textos, etc.). En una celda:
• Cuando se escribe una variable, aparecerá resaltada en azul mientras no tenga asig-
nado un valor, cuando tiene un valor pasará a ser verde.
• Una vez escrita la instrucción que se quiere para que el programa la ejecute se
presiona SHIFT+ENTER.
• Una vez ejecutada una celda se observa que a su izquierda aparece el prefijo “In” y
a la izquierda del resultado aparece el prefijo “Out”.
• Algunas letras mayúsculas están reservadas para el lenguaje del programa, por lo que
es aconsejable utilizar siempre letras minúsculas para asignar variables o nombres.
2
1.2.1 Operaciones básicas
Mathematica reconoce los operadores aritméticos habituales: suma (+), diferencia (-),
producto (* o espacio en blanco), división (/) y potencia ( ˆ ). Si intervienen varios de
estos operadores en una misma operación, Mathematica aplica los criterios de prioridad
habituales entre ellos: potencias−→productos y divisiones−→sumas y restas. Por otra
parte, los criterios de prioridad se pueden alterar con el uso de paréntesis.
Para escribir un comando o instrucción del programa Mathematica, se debe tener en cuenta
lo siguiente:
1. Todos los comandos comienzan por una letra mayúscula. No es lo mismo escribir
“Solve” (comando utilizado para resolver ecuaciones y sistemas de ecuaciones) que
“solve” (esta palabra no será reconocida por el programa como un comando y se
reconocerá como una variable o se generará un mensaje de error).
3
utilizarán paréntesis ( ) y, si se quiere definir una lista (como podrı́a ser vectores,
matrices, etc.), se utilizarán llaves {}.
Mathematica puede trabajar con todos los tipos de números: enteros (Integer), racionales
(Rational), reales (Real) y complejos (Complex). Para saber de qué tipo es un número
concreto, podemos utilizar la instrucción: Head[número].
N[expresión]
• Número π: Pi.
4
• Número e: E.
• Unidad imaginaria: I.
• Infinito: Infinity.
Por otro lado, también incorpora funciones elementales. Sus nombres son la abre-
viatura correspondiente en inglés. Si el argumento utilizado en cualquiera de las funciones
es un número exacto, Mathematica devolverá un valor exacto (se puede obtener el valor
aproximado utilizando el comando N). En cambio, si el argumento es un número decimal,
Mathematica nos devolverá un valor aproximado con una precisión de 6 dı́gitos (aunque
internamente trabaja con 16 dı́gitos).
Función Comando
Seno Sin[x]
Coseno Cos[x]
Tangente Tan[x]
Arcoseno ArcSin[x]
Arcocoseno ArcCos[x]
Arcotangente ArcTan[x]
Logaritmo neperiano Log[x]
Logaritmo en base a Log[a,x]
Exponencial Exp[x]
Raı́z cuadrada Sqrt[x]
Valor absoluto Abs[x]
Las variables se utilizan para el almacenamiento temporal de información que vaya a ser
utilizada en cálculos posteriores. Para dar nombre a una variable, hay que cumplir ciertas
reglas:
2. No es posible utilizar letras reservadas por el programa; para evitar este problema,
se recomienda que las variables siempre se nombren con letras minúsculas.
5
(b) Asignación diferida. Por ejemplo, se asigna a la variable “a” el valor 4 y a la
variable “x” se le asigna el valor que tenga “a” en cada momento, como en la
siguiente imagen. Si posteriormente se cambia el valor de la variable “a”, el
valor de la variable “x” sı́ cambiará también. La asignación diferida se hace:
nombre variable := valor o expresión
Para Mathematica, un vector de Rn no es más que una lista de n números y las listas
en Mathematica se escriben entre llaves y con cada elemento de la lista separado por una
coma. Por tanto, para escribir el vector (2, 5, −3, 1) de R4 en Mathematica escribiremos
{2, 5, −3, 1}.
Es posible poner un nombre al vector, por ejemplo v; para ello solo tendremos que
escribir v = {2, 5, −3, 1} o bien si el vector (como en la figura anterior) está en la entrada
y salida número 1, podrı́amos escribir v = %1; ası́, al escribir en Mathematica v nos
devolverá los elementos del vector v.
6
Nota: es importante recordar que no deben utilizarse mayúsculas para nombrar el-
ementos, para evitar confusiones con las funciones y constantes incorporadas en Mathe-
matica, que siempre empiezan con mayúscula.
La suma de los vectores (2, 1) y (3, −5) se escribe en Mathematica: {2, 1} + {3, −5}.
En Mathematica, una matriz es solo una lista de vectores; por ello, se puede escribir una
matriz como una lista (entre llaves) donde cada elemento es una nueva lista (cada fila de
la matriz entre llaves y separadas por coma). También se puede utilizar la paleta para
escribir una matriz: por defecto es una matriz de orden 2, pero se pueden añadir filas
y columnas utilizando las teclas control y enter para añadir filas y control y coma para
añadir columnas. Por otra parte, se pueden añadir filas y columnas utilizando las opciones
de “Add Row” y “AddColumn” que se incluye en la paleta.
7
1.4.1 Operaciones básicas con matrices
Los comandos para las principales operaciones relacionadas con matrices se pueden en-
contrar en la paleta:
• Suma: A + B.
8
• Producto de una matriz por un escalar: 3 ∗ A o bien 3 A (dejando un espacio entre
el número y la matriz).
• Producto de dos matrices: A.B (el producto entre matrices se indica con un punto).
9
1.5 Sistemas de ecuaciones lineales
En el comando Solve, para escribir la igualdad en una ecuación, se escribe dos veces el
signo igual (= =). Si solo se escribe una vez Mathematica interpreta que se está asignado
un valor o un nombre a algo.
Además de escribir la ecuaciones del sistema como una lista, las incógnitas también se
escribirán entre llaves y separadas por comas. Como se ve en la imagen anterior, Mathe-
matica devuelve la solución del sistema escrito; como es única, tal sistema de ecuaciones
lineales será compatible determinado.
Si el sistema es incompatible, el programa nos devuelve {}, que indica una lista sin
elementos (o conjunto vacı́o).
10
11
Unit 1. Basic Elements on Linear
Algebra and Matrix Theory
1.1 Introduction
In these notes you will find an introduction to the Wolfram Mathematica program that
you can use from Myapps. This will appear at your virtual desktop once you enter your
username and password. On the other hand, we will also use Wolframalpha, which has
extensive knowledge and deep computational power that will help us this course. In this
case, Wolframalpha is used online and the address is Wolframalpha.
The Wolfram Mathematica program offers several options to work, such as, among
others:
• Define variables and functions: Operate with variables and functions that the user
has previously defined.
12
1.2 Introduction to Mathematica
First, we open a new Wolfram Mathematica document. This document is called “note-
book” (see figure 1).
As previously indicated, a notebook is divided into cells that can be of different types
(commands, texts, etc.). In a cell:
• When a variable is written, it will appear highlighted in blue while it has not been
assigned a value. When it has a value, it will turn green.
• Once you have written the instruction, press SHIFT+ENTER to execute it.
• Once a cell has been executed, the prefix “In” appears on its left and the prefix
“Out” appears on the left of the result.
• Commands in Wolfram Mathematica have a specific syntax, they always start with
a capital letter and their argument is always enclosed in square brackets “[ ]”.
13
1.2.1 Basic operations
In Wolfram Mathematica, operations can be typed directly with the keyboard or by using
the program’s palettes (they can be found in the menu “palettes”), and the most useful one
is the “Class Assistant”. Some operations can also be performed using specific program
commands.
Some basic operations such as power and division are also available in the palette.
1. All commands start with an uppercase letter. It is not the same to write “Solve”
(command used to solve equations and systems of equations) than “solve” (this word
will not be recognized by the program as a command and an error message will be
generated).
2. The arguments of a command are always written between brackets [] and are for the
exclusive use of the commands. If you want to indicate priority in the operations,
use parentheses (), and if you want to define a list such as vectors, matrices, etc.,
use braces {}.
14
1.2.3 Numbers and precision in calculations
Wolfram Mathematica can work with all types of numbers: integer, rational, real, and
complex. To find out what type a particular number is, we can use the instruction:
Head[number].
Regarding the size of a number, the program has no limitation except for the one given
by the computer’s memory.
As you can see in the previous image, Wolfram Mathematica works in exact mode. If
you want an approximation of the result, you have to indicate it with the command:
N[expresión]
• Number π: Pi.
• Number e: E.
• Imaginary unit: I.
• Infinity: Infinity.
15
On the other hand, it also incorporates elementary functions, whose names are the
corresponding abbreviation in English. If the argument used in any of the functions is an
exact number, Wolfram Mathematica will return an exact value (the approximate value
can be obtained using the N command). On the other hand, if the argument is a decimal
number, Wolfram Mathematica will return an approximate value with a precision of 6
digits (although internally it works with 16 digits):
Function Command
Sine Sin[x]
Cosine Cos[x]
Tangent Tan[x]
Arcsine ArcSin[x]
Arccosine ArcCos[x]
Arctangent ArcTan[x]
Natural Logarithm Log[x]
Logarithm base a Log[a,x]
Exponential Exp[x]
Square Root Sqrt[x]
Absolute value Abs[x]
Variables are used for temporary storage of information to be used in later calculations.
To name a variable, certain rules must be followed:
2. It is not possible to use letters reserved by the program. To avoid this problem,
variables are always named with lowercase letters.
(a) Immediate assignment: For example, the variable a is assigned the value 4 and
the variable x is assigned the value of a, as in the following image. If the value
of the variable a is subsequently changed, the value of the variable x will not
change. The immediate assignment is done as follows:
variable name = value or expression
(b) Deferred Assignment: For example, the variable a is assigned the value 4 and
the variable x is assigned the value of a at any time, as in the following image.
If the value of the variable a is changed later, the value of the variable x will
also change. The deferred assignment is done as follows:
16
variable name := value or expression
It is possible to name a vector by a letter, for example v; for this we will only have
to write v = {2, 5, −3, 1} or if the vector (as in the previous figure) is in the input and
output number 1, we could write v = %1; thus, writing in Mathematica v, the program
will return the elements of the vector v.
Note: it is important to remember not to use capital letters when naming elements, to
avoid confusion with Mathematica’s built-in functions and constants, which always start
with a capital letter.
The sum of the vectors (2, 1) and (3, −5) is written in Mathematica as follows:
17
1.3.2 Product of a vector by a scalar
The product of a vector by a scalar can be written by leaving a blank space between the
number and the vector or by writing the sign * between the number and the vector; that
is, the number-blank space-vector or number-asterisk-vector.
18
1.4.1 Basic operations with matrices
The commands for the main matrix-related operations can be found in the palette:
Given two matrices A and B that we have entered and named in Mathematica, the
expressions and commands for the basic operations between such matrices are as follows:
• Sum: A + B.
19
• Product of a matrix by a scalar: 3 ∗ A or 3 A (leaving a blank space between the
number and the matrix).
• Product of two matrices: A.B (the product between matrices is indicated by a dot).
If any operation between matrices cannot be performed (for example, if we try to add
two matrices of different order), Mathematica returns an error message:
In the following figure you can see some examples of operations with matrices:
20
1.5 Systems of linear equations
In the Solve command, to write the equality in an equation, write the equal sign (= =)
twice. If you write it only once, Wolfram Mathematica interprets that a value or a name
is assigned to something.
If you want to solve a system of equations, you use the same previous command, but
since you have to write several equations, you have to write them as a list.
In addition to writing the equations of the system as a list, the unknowns will also
be written in braces and separated by commas. As seen in the image above, Wolfram
Mathematica returns the solution of the written system, since it is unique, such a system
of linear equations will be uniquely determined.
For an underdetermined system, the solutions are given as a function of one of the
variables. In that case, a message also appears indicating that the system has not been
solved for all the variables, since some of them are used as parameters.
Si el sistema es incompatible, el programa nos devuelve {}, que indica una lista sin
elementos (o conjunto vacı́o).
If the system is inconsistent, the program returns {}, indicating a list with no elements
(or empty set).
21
22
Funciones reales de una variable
En primer lugar recordemos que en Mathematica una variable comienza con una letra pero
también puede contener números. Es importante que la primera letra (si tiene varias) sea
siempre minúscula (algunas mayúsculas están reservadas por el programa):
También conviene recordar que un espacio entre dos variables o números indica mul-
tiplicación; es decir, se se escribe “a b” significas“ a” veces “b”, pero si se escribe “ab”
significa la variable “ab”:
Para trabajar con una función en Mathematica, se puede introducir directamente su ex-
x
presión en una celda de entrada. Por ejemplo, si escribimos 2 y ejecutamos esta
x +1
entrada:
23
Si se quiere sustituir el valor de la variable x por un número, por ejemplo 4, se utiliza
/. (que es la orden sustituir) y la variable a sustituir seguida de una flecha y el valor que
se quiera:
La flecha para asignar un valor a la variable se puede escribir desde la paleta o bien
utilizando el guion y el sı́mbolo de mayor en el teclado (− >).
24
• “Limpiar” el nombre de la función ya utilizada (con el comando “Clear”) y usar ese
mismo nombre para la nueva:
Algunas de las funciones elementales más usuales que utilizaremos (seno, coseno, tan-
gente, exponencial, logaritmo neperiano, etc.) ası́ como los sı́mbolos de la raı́z cuadrada
y la raı́z n-ésima, o constantes como el número pi o el número e, que podemos necesitar,
están disponibles en las paletas como ya se indicó.
Para representar funciones reales de una variable real utilizaremos el comando “Plot”, que
genera un gráfico en dos dimensiones (2D) y que tiene la siguiente sintaxis:
1−x
Ası́, para representar la función f (x) = sen en el intervalo [2,3], escribiremos:
x
25
Si se quiere ver “más cerca” una parte de la gráfica, basta con cambiar el intervalo
de representación. Ası́, si queremos observar con más detalle el comportamiento de esta
función cerca de x =0, podemos dibujarla en el intervalo (0, 0.1], por ejemplo:
Por último, en 2D tenemos la opción de dibujar dos o más curvas en unos mismos
ejes de coordenadas; para ello, basta con escribir entre llaves las diferentes funciones que
queremos representar (es decir, se escribe una lista de funciones), por ejemplo:
26
2.2 Cálculo de derivadas
D[expr , var],
donde habrá que indicar la función que deseamos derivar ası́ como la variable de la que depende
la función. Veamos a continuación varios ejemplos:
D[expr,{var,order}]
27
2.3 Cálculo de lı́mites de funciones de una variable
Para calcular el lı́mite de una función en Mathematica, utilizamos la orden “Limit”, que
tiene la siguiente sintaxis:
donde “valor” puede ser cualquier número real o bien infinito (Infinity). Por ejemplo, el
lı́mite cuando la variable tiende a un número:
Por último, si la variable tiende a un número por la derecha o por la izquierda (lı́mites
laterales):
28
2.4 Crecimiento, decrecimiento, concavidad y convexidad
29
En la figura anterior, se observa que f ′ (−1) = 4e > 0, f ′ (0) = −1 < 0 y f ′ (2) = 19e4 >
0; por tanto, hemos obtenido los signos +,-,+ y se sabe que f ′ es continua, luego:
A continuación calculamos los valores donde se anula la segunda derivada para calcular
los intervalos de concavidad y convexidad.
30
En la figura anterior, se observa que f ′′ (−1) = −24e < 0, f ′′ (0.5) = −0.48151 < 0 y
f ′′ (2) = 4e > 0, por tanto hemos obtenido los signos -,-,+ y se sabe que f ′′ es continua,
por tanto:
FunctionMonotonicity[expresión, variable],
FunctionConvexity[expresión, variable],
2.5 Integración
31
Integrate[expresión,variable]
32
2.5.2 Integral definida
Integrate[expresión,{variable,a,b}]
Al igual que ocurrı́a con las integrales indefinidas, Mathematica no siempre puede
expresar el resultado de una integral definida de forma simple, por ejemplo:
33
[Link] Aplicación de la integracición al cálculo de áreas
Sabemos que el área limitada por las curvas y = f (x e y = g(x) en el intervalo [a,b] viene
dada por la integral definida entre a y b del valor absoluto de f (x) − g(x) (si g(x) = 0 se
obtiene el área limitada por la curva y = f (x) y el eje OX en el intervalo [a, b]), es decir:
Para plantear correctamente la integral anterior para calcular el área limitada por las
curvas y = f (x e y = g(x) en el intervalo [a,b], es conveniente representar previamente el
conjunto cuya área queremos calcular. Mathematica permite visualizar el área limitada
por las curvas y = f (x) e y = g(x) en el intervalo [a, b], representando ambas funciones
simultáneamente con la orden Plot:
Si se tratara del área limitada por la curva y=f(x) y el eje OX, se podrı́a utilizar la
siguiente expresión:
34
2.5.3 Integrales Impropias
El procedimiento para calcular integrales impropias con Mathematica es el mismo que para
las integrales definidas. Si la integral es convergente, Mathematica nos dará directamente
el resultado; en el caso en que la integral impropia no sea convergente, Mathematica nos
devolverá un mensaje advirtiendo de tal situación.
En el ejemplo anterior, Mathematica nos indica que se trata de una integral impropia
de primera especie no convergente. En el siguiente ejemplo se tiene una integral impropia
de segunda especie que es convergente y por tanto, el programa nos devuelve el valor.
35
Real-valued functions of one
variable
First of all let’s remember that, in Mathematica, a variable begins with a letter but it can
also contain numbers. It is important that the first letter (if it has several) is always a
lowercase (some uppercase letters are reserved by the program):
It is also worth remembering that a space between two variables or numbers indicates
multiplication; that is, writing “a b” means “a” times “b”, but writing “ab” means the
variable ‘ ‘ab”:
To work with a function using Mathematica, you can enter its expression directly in an
x
input-cell. For instance, if we type 2 and execute this input, we will obtain the
x +1
following result:
36
If we want to replace the value of the variable x by a number, for example 4, we use
/. (which is the substitute command) and the variable to substitute followed by an arrow
and the desired value:
The arrow to assign a value to the variable can be selected from the palette or by using
the hyphen and the greater-than symbol on the keyboard (− >).
We have to be careful not to use the same name for different functions. If we want to
introduce a new function, we have two options:
37
• “Clear” the name of the already used function (with the “Clear” command) and use
that same name for the new one:
Some of the most common elementary functions we will use (sine, cosine, tangent,
exponential, natural logarithm, etc.) as well as the symbols of the square root and n-th
root, or constants such as the number pi or the number e, that we may need, are available
in the palettes as already indicated.
To plot real functions of one real variable, we will use the “Plot” command, which generates
a two-dimensional (2D) plot and has the following syntax:
1−x
Thus, to plot the function f (x) = sin on the interval [2,3], we will type:
x
Note: by asking the program to plot the function on the interval [2,3], Mathematica
limits by default the graphical representation of the function to the set [2, 3] × [f (2), f (3)]
and, therefore, the intersection point of the axes shown on the graph is not, in general,
the (0,0). The representation of the curve slice in the graph above, for example, is located
in the fourth quadrant.
If we represent the same function in the interval (0,5] the global aspect of the function
will be better observed:
38
If we want to see “closer” a part of the graph, it is enough to change the display interval.
Thus, if we want to observe in more detail the behavior of this function near x = 0, we
can plot it in the interval (0, 0.1], for example:
Finally, in 2D we have the option of plotting two or more curves on the same coordinate
axes; to do this, just write between braces the different functions that we want to represent
(i.e., write a list of functions), for example:
39
2.2 Derivatives
To compute the derivative of a real function of one variable, we will use the command
D[expr , var],
where it will be necessary to indicate the function we want to derive as well as the variable on
which the function depends. Let’s see below several examples:
D[expr,{var,order}]
In this case, it will be necessary to indicate the derivation order, in addition to the function
and its variable.
40
2.3 Limits of functions of one variable
To compute the limit of a function in Mathematica, we use the “Limit” command, which
has the following syntax:
where “value” can be any real number or infinity. For example, the limit when the variable
tends to a number:
Finally, if the variable tends to a number from the right or from the left (lateral limits):
41
zero allows us to determine certain properties of the form of the function, such as its
increase/decrease and concavity/convexity; with this, we can obtain an approximation to
the graphical representation of the function f . When using Mathematica, it may not make
much sense to study shape properties to obtain a graphical representation of the function,
since by using the Plot command it is possible to directly obtain such a representation with
great precision. However, it is interesting to know exactly the increasing and decreasing,
concavity and convexity intervals of the function (as well as the maximum, minimum and
inflection points).
Next, with an example, we will see the Mathematica commands to easily compute the
increasing, decreasing, concavity and convexity intervals of real functions of real variables.
42
In the previous figure, it is observed that f ′ (−1) = 4e > 0, f ′ (0) = −1 < 0 and
f ′ (2) = 19e4 > 0; therefore, we have obtained the signs +,-,+ and it is known that f ′ is
continuous, then:
• f ′ is positive on the interval (−∞, x1) ⇒ f is increasing on the interval (−∞, x1).
• f ′ is negative on the interval (x1, x2) ⇒ f is decreasing on the interval (x1, x2).
Next, to compute the intervals of concavity and convexity, we compute the values
where the second derivative equals zero.
43
In the previous figure, it is observed that f ′′ (−1) = −24e < 0, f ′′ (0.5) = −0.48151 < 0
and f ′′ (2) = 4e > 0. Therefore, we have obtained the signs -,-,+ and it is known that f ′′
is continuous, therefore:
• f ′′ is negative on the interval (−∞, x3) and on (x3, x4) ⇒ f is concave on the interval
(−∞, x4).
• f ′′ is positive on the interval (x4, +∞) ⇒ f is convex on the interval(x4, +∞).
FunctionMonotonicity[expression, variable],
which returns: the value 1 if the function is increasing in its entire domain; the
value -1 if the function is decreasing in all its domain; “Indeterminate” otherwise. If the
function depends on parameters, the “FunctionMonotonicity” command does indicate the
increasing and decreasing intervals depending on the values of the function parameters.
FunctionConvexity[expression, variable],
which returns: the value 1 if the function is covex in its domain; the value -1 if
the function is concave in its domain; “Indeterminate” otherwise.
44
2.5 Integration
Mathematica can compute primitives of functions using certain commands. The following
sections will show how to calculate indefinite, definite and improper integrals. On the
other hand, Mathematica computes almost any integral that can be done and displays the
result in terms of standard mathematical functions. But it must be taken into account
that, when performing the integral of a simple function, the result may contain much more
complicated functions (contrary to what happens when deriving, that the expression of a
derivative is always simpler than that of the function being derived) or the result of the
integral cannot be expressed in terms of standard mathematical functions.
Integrate[expresión,variable]
In the “Class Assistant” palette you will find the above command (see figure below):
When using the command “Integrate” or its equivalent of the “Class Assistant” palette,
Mathematica yields an expression whose derivative is the function to be integrated, but
there are infinite functions that verify such property, although the program only displays
one of them. Therefore, Mathematica displays the antiderivative or primitive of a function
45
and not its indefinite integral. So, it must be taken into account that the result of the
integral will be the expression given by the program plus an arbitrary constant.
Integrate[expression,{variable,a,b}]
The aforementioned command can be found in the “Class Assistant” palette (see figure
below):
46
As with indefinite integrals, Mathematica cannot always express the result of a definite
integral in a simple way, for example:
We know that the area bounded by the curves y = f (x and y = g(x) in the interval [a,b]
is given by the definite integral between a and b of the absolute value of f (x) − g(x) (if
g(x) = 0 the área limited by the curve y = f (x) and the OX axis in the interval [a, b ]),
i.e.:
Nota. In Mathematica, the absolute value can be written either with the command
“Abs[expression]” or with | |.
To compute the area bounded by the curves y = f (x) and y = g(x) in the interval
[a,b], it is convenient to previously represent the area we want to calculate. Mathematica
allows us to visualize the area bounded by the curves y = f (x) and y = g(x) in the interval
[a,b] representing both functions simultaneously with the Plot command:
47
If it were the area bounded by the curve y = f (x) and the OX axis, the following
expression could be used:
Example. Compute the area of the region bounded by the curves y = x2 and y = x.
The procedure to compute improper integrals with Mathematica is the same as for definite
integrals. If the integral is convergent, Mathematica will show the result directly; in the
case where the improper integral is not convergent, Mathematica will return a warning
message.
48
improper integral. In the following example, we have a second-type improper integral that
is convergent and, therefore, the program returns the value.
49
Funciones reales de varias
variables
Las funciones reales de varias variables se introducen de modo similar a las funciones de
una variable. No es necesario introducir las funciones como tales para trabajar en Wolfram
Mathematica ya que podemos trabajar solo conla expresión de la función.
50
3.1.1 Funciones vectoriales
Para trabajar con funciones vectoriales, hay que tener en cuenta que las imágenes de
tales funciones son vectores, por lo que al escribir la expresón de la función en Wolfram
Mathematica hay que utilizar llaves (recordemos que un vector en Wolfram Mathematica
es una lista y que las listas se escriben entre llaves y separando sus elementos por comas).
51
De cualquier modo, para evitar confusiones, es recomendable cambiar de nombre al
escribir cada nueva función o limpiar el nombre, si no vamos a volver a utilizar la función
anterior.
52
En el comando Plot3D, hay que indicar cuáles son las variables de la función y cuáles
son los intervalos de variación de cada uno de ellas. Por ejemplo para la función f (x, y) =
sen(xy) para x ∈ [−2, 2] e y ∈ [−3, 3], su gráfica serı́a:
En Wolfram Mathematicas es posible rotar la gráfica para verlo desde otro punto de
vista. Para ello, basta con hacer click sobre la gráfica y moverla hasta la perspectiva
deseada.
Para visualizar la variación de una función de varias variables se utilizan las curvas de
nivel, con Wolfram Mathematica veremos las curvas de nivel de funciones de dos variables.
Recordar que dada una función f , una curva de nivel de f son todos aquellos puntos que
53
tienen la misma imagen, es decir, los puntos que tienen las misma altura en el caso en el
que la función tiene dos variables y se expresa de forma implı́cita mediante la ecuación
f (x, y) = C.
Para representar las curvas de nivel de una función de dos variables, utilizaremos uno
de los siguientes comandos:
54
Si se quiere representar una curva de nivel en particular se le indica al programa el
nivel correspondiente, por ejemplo:
Para calcular una derivada parcial de una función de varias variables basta con indicar
∂f
respecto de qué variable se quiere derivar la función. Por ejemplo para calcular (x, y, z),
∂z
2
x − xy
donde f (x, y, z) = :
z2y
55
3.3.1 Vector gradiente
Para calcular el vector gradiente de cierta función, se podrı́an calcular sus derivadas par-
ciales y conocidas estas escribir el vector gradiente, pero es posible también indicar di-
rectamente a Wolfram Mathematica que lo calcule. Para ello, en el comando de derivar
(”D”) escribiremos las variables entre una doble llave y de esta forma, Wolfram Mathe-
matica nos calculará el vector gradiente. Ası́, el vector gradiente de la función anterior
x2 − xy
f (x, y, z) = se calculará:
z2y
Aunque no hay una función especı́fica en Mathematica para determinar si una función
es o no homogénea, se puede averiguar fácilmente con la teorı́a explicada en clase y con
56
los comandos que se utilizan para calcular gradientes, para simplificar expresiones y para
factorizar.
57
Por último, veamos un ejemplo utilizando el Teorema de Euler para ver si una función
es homogénea o no:
58
La “,” que separa las distintas condiciones en el comando “RegionPlot” significa ”o”,
nosotros necestiamos el conjunto de puntos que verifican todas las condiciones a la vez,
por ello, cambiamos la ”,” por “&&”, quedando como sigue:
59
Ejemplo 3: Representamos la región A = (x, y) ∈ R : 0 ≤ x ≤ 2, 0 ≤ y ≤ x2 , y ≤ x2 − 4x + 4 .
Para calcular integrales dobles con Wolfram Mathematica se utiliza la misma orden que
para las integrales definidas de funciones de una variable:
60
3.6.1 Integral doble en un rectángulo
Un rectángulo en R2 viene definido por A = [a, b] × [c, d]. Dada una función real de
dos variables reales f (x, y) para calcular la integral doble de la función f en el intervalo
[a, b] × [c, d], se tiene que la variable x se mueve en el intervalo [a, b] y la variable y en el
intervalo [c, d], por tanto la integral doble se calculará como:
Z Z Z b Z d
f (x, y) dxdy = f (x, y)dy dx
A a c
x2
Ejemplo: Calcular la integral doble de la función f (x, y) = en el conjunto A =
y2
[−2, 4] × [1, 3].
61
Si aplicamos el teorema de Fubini y cambiamos el orden de integración, se obtiene el
mismo resultado:
3.6.2 Integral doble en una región del tipo A = {(x, y) ∈ R2 : a ≤ y ≤ b, g(y) ≤ x ≤ h(y)}
2
regiones2 del tipo A1 = (x, y) ∈ R : a ≤ y ≤ b, g(y) ≤ x ≤ h(y) o bien del tipo A2 =
En
(x, y) ∈ R : a ≤ x ≤ b, g(x) ≤ y ≤ h(x) , una de las variables se mueve entre valores
constantes y la otra entre funciones, por tanto se pueden plantear las integrales sin ser
necesario representar las regiones. Hay que tener en cuenta que los lı́mites de integración
de la integral de fuera en una integral doble siempre deben ser valores constantes y no
funciones. Por tanto, la integral doble de la función f (x, y) en la región A1 se plantearı́a
como:
!
Z Z Z b Z h(y)
f (x, y) dxdy = f (x, y)dx dy
A1 a g(y)
!
Z Z Z b Z h(x)
f (x, y) dxdy = f (x, y)dy dx
A2 a g(x)
62
En la región representada, se puede ver que la variable x varı́a de 0 a 2 y la variable y
varı́a de la parábola (y = x2 ) a la recta (y = 2x). Por tanto, la integral pedida será:
Cuando la región donde se quiere calcular la integral doble viene dada de forma más
general que en los casos anteriores, hay que representar la región necesariamente para
poder ver cómo varı́an las variablas x e y. Veamos el siguiente ejemplo.
63
En la gráfica anterior se tiene observa que la variable x varı́a de 0 a 2, pero la variable
y varı́a de forma diferente si la variable x varı́a entre 0 y 1 que si lo hace entre 1 y 2, es
decir, para calcular la integral pedida, si se quiere calcular primero respecto a y y luego
respecto a x, hay que dividir la integral en dos partes, para ello, en primer lugar hay
que asegurar que el punto de corte de las dos parábolas de la región dada es x = 1, esto
podemos hacerlo con el comando Solve:
Por último, señalar que la integral anterior podrı́a haberse calculado promero respecto
de la variable x y luego respecto de la variable y, de esta forma, no habrı́a que partir la
integral en dos partes. Si se mira la región puede verse que la variable y varı́a entre 0 y 1,
√
mientras que la variable xlo hace de la parábola y = x2 , es decir desde x = + y a la otra
√
parábola y = x2 − 4x + 4, es decir a x = − y + 2. Por tanto se puede calcular la integral
pedida como:
64
65
Real-valued functions of several
variables
Real-valued functions of several variables are entered in a similar way to functions of one
variable. It is not necessary to define the functions to work in Wolfram Mathematica since
we can also work with the expression of the function.
If we decide to give a name to the function, we will indicate in square brackets the
different variables followed by − and separated by commas. Thus, to define f (x, y, z) =
xyln(z), we will write:
Note: When in the expression of the function there are multiplying variables, this
must be indicated to the program using the space or the ∗ between the variables that are
multiplied.
66
3.1.1 Vector-valued functions
To work with vector-valued functions, keep in mind that the images of such functions are
vectors. So, when typing the expression of the function in Wolfram Mathematica, we must
use curly braces (remember that a vector in Wolfram Mathematica is a list and that lists
are enclosed in braces and their elements are separated by commas).
67
In any case, to avoid confusion, it is recommended to change the name when writing
each new function, or to clear the name, if we are not going to use the previous function
again.
68
In the Plot3D command, it is necessary to indicate which are the variables of the
function and which are the variation intervals of each of them. For example, for the
function f (x, y) = sin(xy) for x ∈ [−2, 2] and y ∈ [−3, 3], the graph would be:
In Wolfram Mathematica it is possible to rotate the graph to see it from another point
of view. To do this, just click on the graph and move it to the desired perspective.
To visualize the variation of a function of several variables, we use contour lines. With
Wolfram Mathematica, we will see the contour lines of functions of two variables. Recall
that, given a function f , a contour line of f is all those points that have the same image,
69
that is, the points that have the same height in the case in which the function has two
variables, and it is implicitly expressed by the equation f (x, y) = C.
In short, the contour lines represent a three-dimensional surface on the plane (the
graph of the function of two variables) and allow us, among other things, to know the
increasing and decreasing regions of the given function, as well as its extremes.
To represent the contour lines of a function of two variables, we will use one of the
following commands:
In the first one, the indicated contour line will be represented. In the second one,
Wolfram Mathematica will show ten contour lines that it will shade to indicate the different
heights. As we scroll through the graph, a label will appear indicating the different levels.
p In the following image we can see the graphical representation of the function f (x, y) =
100 − x2 − y 2 and some of its contour lines.
70
3.3 Partial derivatives and gradient vector
We can also use the partial derivative option of the palette (placing the expression to
be derived in parentheses):
71
3.3.1 Gradient vector
To compute the gradient vector of a certain function, one could calculate its partial deriva-
tives and then write the gradient vector, but it is also possible to directly instruct Wol-
fram Mathematica to compute it. To do this, in the derive command (”D”) we will
write the variables between a double brace and, in this way, Wolfram Mathematica will
directly compute the gradient vector. Thus, the gradient vector of the above function
x2 − xy
f (x, y, z) = will be computed as follows:
z2y
If you want to compute the gradient vector at a certain given point, it will be enough
to substitute that point in the previous expression:
The following example uses the definition of homogeneous function and the command
”Simplify”:
72
Let’s look at an example using the ”Factor” command:
Por último, veamos un ejemplo utilizando el Teorema de Euler para ver si una función
es homogénea o no:
73
3.5 Representing regions
The “,” that separates the different conditions in the command “RegionPlot” means
”or”, we need the set of points that verify all the conditions at the same time, so we change
the “,” to “&&”, as follows:
74
Let us look at some examples of representation of regions:
A = (x, y) ∈ R : 0 ≤ x ≤ 2, 0 ≤ y ≤ x2 , y ≤ x2 − 4x + 4
75
A = (x, y) ∈ R : 0 ≤ x ≤ 2, 0 ≤ y ≤ x2 , y ≤ x2 − 4x + 4
To compute double integrals with Wolfram Mathematica, the same order is used as for
definite integrals of functions of one variable:
In the previous image, ”expr” refers to the function to be integrated and it is convenient
that it is always placed between parentheses. In the case of double integrals, ”expr” will
become an integral. Thus, the expression would look like the following:
76
To correctly determine the limits of integration of both integrals, it is convenient to
graphically represent the region in which the double integral is to be calculated. To do
this, we can use the following command:
The “,” that separates the different conditions in the command “RegionPlot” means
”or”. We need the set of points that verify all the conditions at once. Therefore, we change
the ”,” for “&&”, remaining as follows:
In the following sections, we will see examples of the computation of double integrals
in different types of regions.
A rectangle in R2 is defined by A = [a, b] × [c, d]. Let f (x, y) be a real function of two real
variables, to compute the double integral of the function f on the interval [a, b] × [c, d], the
variable x moves in the interval [a, b] and the variable y in the interval [c, d]. Therefore,
the double integral will be computed as follows:
Z Z Z b Z d
f (x, y) dxdy = f (x, y)dy dx
A a c
x2
Example. Compute the double integral of the function f (x, y) = over the set
y2
A = [−2, 4] × [1, 3].
First, we graph the region A (although in this case it is not necessary to do so):
77
The blue rectangle in the image above is our region of integration. Next, we compute
the requested double integral:
If we apply Fubini’s theorem and change the order of integration, the same result is
obtained:
2
regions of2 the type A1 = (x, y) ∈ R : a ≤ y ≤ b, g(y) ≤ x ≤ h(y) or of the type A2 =
In
(x, y) ∈ R : a ≤ x ≤ b, g(x) ≤ y ≤ h(x) , one of the variables varies between constant
78
values and the other between functions. Therefore, the integrals can be posed without
being necessary to represent the regions. Note that the limits of integration of the outside
integral in a double integral must always be constant values. Therefore, the double integral
of the function f (x, y) over the region A1 would be posed as:
!
Z Z Z b Z h(y)
f (x, y) dxdy = f (x, y)dx dy
A1 a g(y)
The double integral of the function f (x, y) over the region A2 would be posed as:
!
Z Z Z b Z h(x)
f (x, y) dxdy = f (x, y)dy dx
A2 a g(x)
2 2
Compute the double 2integral of the function f (x, y) = x − 5y over the
Example:
region A = (x, y) ∈ R : 0 ≤ x ≤ 2, x ≤ y ≤ 2x .
First, we graphically represent the region (although in this case it is not necessary to
do so because we know the limits of integration of both variables).
In the depicted region, it can be seen that the variable x varies from 0 to 2 and the
variable y varies from the parabola (y = x2 ) to the line (y = 2x). Therefore, the requested
integral will be:
79
3.6.3 Double integral over a more general region
When the region where we want to calculate the double integral is given in a more general
way than in the previous cases, we must necessarily represent the region in order to see
how the variables x and y vary. Let us look at the following example.
Observe that, in the previous figure, the variable x varies from 0 to 2, but the variable
y varies differently if the variable x varies between 0 and 1 than if it does between 1 and
2. That is, to compute the requested integral, if we want to calculate first with respect
to y and then with respect to x, we have to divide the integral in two parts. To do this,
we must first ensure that the intersection point of the two parabolas is x = 1 (this can be
done with the Solve command):
80
Thus, the requested integral will be:
Finally, note that the previous integral could have been calculated first with respect
to the variable x and then with respect to the variable y. In this way, the integral would
not have to be split into two parts. Observing the region, we can see that the variable y
varies between 0 and 1, while the variable x varies from the parabola y = x2 (that is, from
√ √
x = + y) to the other parabola y = x2 − 4x + 4 (that is, to x = − y + 2). Therefore,
the requested integral can be computed as:
81
Sucesiones y series
Las sucesiones numéricas pueden definirse de forma similar a como se hacı́a con las fun-
ciones de una variable. Eso nos permitirá calcular más fácilmente los términos de la
4n − 6
sucesión que nos interesen. Ası́ por ejemplo, la sucesión de término general se
3n + 8
puede definir en Wolfram Mathematica como:
Al definir ası́ una sucesión numérica, si se quiere calcular algún término en particular
de la sucesión, por ejemplo el término 50, solo hay que escribir:
También se puede pedir a Wolfram Mathematica que calcule unos cuantos términos de
una sucesión numérica al mismo tiempo. Para ello, se utilizará el comando Table[expr,{ var,
valor inicial, valor final }]. Por ejemplo, para calcular los 20 primeros términos de la
sucesión anterior se escribirá:
82
Y para calcular los términos de la sucesión anterior comprendidos entre las posiciones
15 y 27 se escribe:
83
En este ejemplo, el lı́mite es un valor finito por lo que se dice que la sucesión an es
4
convergente, es decir, an converge a .
3
En el siguiente ejemplo, la sucesión tiene por lı́mite −∞, por lo que la sucesión es
divergente.
Al trabajar con una serie numérica, a veces se quiere calcular la suma de tal serie (suma
de sus infinitos términos) o bien la suma de un número finito de términos (suma parcial),
en ambos casos, en Wolfram Mathematica se utiliza la misma orden:
En el comando anterior hay que indicar el primer término que se quiere sumar “start”
y el último “end”. A continuación se muestran algunos ejemplos de sumas de términos de
una serie:
84
la última suma del ejemplo anterior es la suma de la serie y el resultado es el número
+∞ n
4 X 2
, por lo que la serie 3 es convergente.
5 5
n=2
+∞
X
Ası́, si se estudia el carácter de la serie (4n − 8):
n=1
85
El mensaje que nos devuelve Wolfram Mathematica nos indica que se trata de una
serie que no converge.
+∞
X
Dada la serie de funciones fn (x).El campo de convergencia puntual de la serie funcional
n=1
es el conjunto de puntos para los cuales la serie converge puntualmente. Para esos valores
se podrá por tanto calcular la suma de la serie.
+∞ n
X 1 2
Ejemplo: Sea la serie de funciones fn (x) donde fn (x) = − . Estudiar
5 x
n=1
dónde es convergente puntualmente la serie de funciones dada.
En este caso, fn es una sucesión geométrica por lo que convergerá cuando la razón
+∞
1 2 n
2 X
esté entre -1 y 1, es decir, si < 1 ←→ |x| > 2. Por tanto, la serie − , si
x 5 x
n=1
estudiamos su suma en Wolfram Mathematica obtenemos:
2
Por tanto, la serie dada converge a − siempre que |x| > 2.
5(−2 + x)
En el siguiente ejemplo se verá una serie de potencias que solo converge puntualmente
para un cierto valor de la variable x y para el resto de valores de la variable x no es
convergente.
+∞
X 3nx
Ejemplo: Sea la serie de funciones gn (x) donde gn (x) = .
5n + 2
n=1
86
Calculamos en primer lugar el lı́mite de la sucesión gn :
+∞
X 3nx
El lı́mete calculado solo es igual a 0 si x = 0, por tanto la serie converge
5n + 2
n=1
puntualmente si x = 0 y es divergente para cualquier valor de x ̸= 0.
∞ n
X
n+1 x−4
Ejemplo: Dada la serie de potencias 3 . Calcular el radio de conver-
5
n=1
gencia y el campo de convergencia.
3n+1
La serie de potencias dada tiene por centro a = 4 y su término general es an = n ,
5
en primer lugar, se calcula su radio de convergencia:
87
en el intervalo(a −
Ası́, la serie de potencias converge puntualmente ρ, a + ρ),
es decir,
5 5 7 17
en el caso particular del ejemplo serı́a el intervalo 4 − , 4 + = , . En los
3 3 3 3
extremos del intervalo hay que estudiar la convergencia de la serie para ver si el intervalo
es cerrado o abierto:
+∞
7 X
Al sustituir el valor de x por se obtiene la serie 3(−1)n que al no ser 0 el lı́mite
3
n=1
de la sucesión 3(−1)n es no convergente.
88
+∞
17 X
Por otro lado, al sustituir el valor de x por se obtiene la serie 3 que al no ser 0
3
n=1
el lı́mite de la sucesión 3 es no convergente.
7 17
Por tanto, el campo de convergencia de la serie dada es el intervalo abierto , ,
3 3
∞
x−4 n
X 7 17
es decir, la serie de potencia 3n+1 converge puntualmente ∀x ∈ , y
5 3 3
n=1
diverge para cualquier valor de x que no esté en tal intervalo.
89
Sequences and series
Numerical sequences can be defined in a similar way to functions of one variable. This
will allow us to easily compute any term of the sequence. Thus, for example, the sequence
4n − 6
of the general term can be defined in Wolfram Mathematica as:
3n + 8
By defining a numerical sequence in this way, if you want to compute a particular term
of the sequence, for example the term 50, you just have to write:
Wolfram Mathematica can also compute several terms of a numberical sequence at the
same time. To do this, the command Table[expr,{ var, initial value, final value }] will be
used. For example, to compute the first 20 terms of the above sequence, we can type:
90
And to compute the terms of the previous sequence between the 15-th and the 27-th,
we type:
It is also possible to plot the above values in Wolfram Mathematica with the ListPlot
command:
In the previous example, the sequence an has been defined before computing the limit,
although this step is not mandatory, That is, the limit could have been computed without
defining the sequence if we directly substitute “expr” by the general term:
91
In this example, the limit is a finite value. So, the sequence an is said to be convergent,
4
that is, an converges to .
3
In the following example, the limit of the sequence is −∞. So, the sequence is not
convergent.
Working with numerical series, sometimes we want to compute either the sum of such a
series (sum of its infinite terms) or the sum of a finite number of terms (partial sum). In
both cases, the same command is used in Wolfram Mathematica:
In the above command, we must indicate the first term to be added “start” and the
last “end”. Below are some examples of addition of terms of a series:
92
The last sum in the previous example is the sum of the series and the result is the
+∞ n
4 X 2
number . So, the series 3 is convergent.
5 5
n=2
+∞
X
Thus, if we study the character of the series (4n − 8):
n=1
93
Wolfram Mathematica displays a message indicating that this is a series that does not
converge.
+∞
X
Let fn (x) be a series of functions. The pointwise convergence field of the functional
n=1
series is the set of points for which the series converges pointwise. For these values, it will
therefore be possible to compute the sum of the series.
+∞
1 2 n
X
Example: Let fn (x), where fn (x) = − , be a series of functions. Study
5 x
n=1
where the given series of functions is pointwise convergent.
In this case, fn is a geometric sequence. So, it will converge when the ratio is between
+∞
1 2 n
2 X
-1 and 1, that is, if < 1 ←→ |x| > 2. If we study the series − in Wolfram
x 5 x
n=1
Mathematica, we obtain:
2
Thus, the given series converges to − if |x| > 2.
5(−2 + x)
In the following example, we will see a power series that only converges pointwise for
a certain value of the variable x, and for the rest of the values of the variable x it is not
convergent.
+∞
X 3nx
Example: Let the series of functions be gn (x), where gn (x) = .
5n + 2
n=1
94
We first calculate the limit of the sequence gn :
+∞
X 3nx
The computed limit is equal to 0 if and only if x = 0. So, the series converges
5n + 2
n=1
pointwise if x = 0 and does not converge for any value of x ̸= 0.
∞ n
X
n+1 x−4
Example: Given the power series 3 , compute the radius of conver-
5
n=1
gence and the pointwise convergence field.
3n+1
The given power series has a = 4 as its center and its general term is an = n . First,
5
we compute its radius of convergence:
95
(a − ρ, a + ρ).
Thus, the power series converges pointwise in the interval That
is, in
5 5 7 17
the particular case of the example, it would be the interval 4 − , 4 + = , .
3 3 3 3
At the endpoints of the interval, we must study the convergence of the series to see if the
interval is closed or open:
+∞
7 X
Substituting the value of x by yields the series 3(−1)n , which is not convergent
3
n=1
since the limit of the sequence 3(−1)n is not equal to 0.
96
+∞
17 X
On the other hand, by substituting the value of x by , the series 3 is obtained,
3
n=1
which is not convergent since the limit of the sequence 3 is not equal to 0.
Therefore, the pointwise convergence field of the given series is the open interval
∞ n
7 17 n+1 x − 4 7 17
X
, . That is, the power series 3 converges pointwise ∀x ∈ ,
3 3 5 3 3
n=1
and does not converge for any value of x outside this interval.
97