You are on page 1of 152

Euler Math Toolbox

An Introduction
Rene Grothmann
March 2010, Euler Version 9.2

Contents

Preface

1 Jumping into Euler

1.1 Computing with Euler and Maxima . . . . . . . . . . . . . . . . . . . . . . . . .

1.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3 Discussing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4 Solving Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.5 Vectors and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2 Introduction

27

2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.2 First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3 The Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.4 The Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.5 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.6 Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.7 Help and Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.8 Euler Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3

CONTENTS

3 Expressions and Plots

3.1
3.2
3.3
3.4
3.5
3.6
3.7

Elementary Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Numerical Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
De nition of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4 Maxima

4.1
4.2
4.3
4.4
4.5
4.6

Direct Input of Maxima Commands . . . . . . . . . . . . . . . . . . . . . . . . .


Di erentiation and Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Maxima Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Exchanging Values between Maxima and Euler . . . . . . . . . . . . . . . . . . .
Matrices in Maxima . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Compatibility and Direct Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5 Data Types

5.1
5.2
5.3
5.4

Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Intervals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6 Euler Matrix Language

6.1
6.2
6.3
6.4
6.5
6.6

Matrices and Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


The Matrix Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Regression Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Eigenvalues and Singular Values . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

41
43
45
47
48
51
54
59

59
63
65
68
71
74
77

77
78
81
82
85

85
88
92
94
96
98

CONTENTS

7 Functions of Several Variables

7.1
7.2
7.3
7.4

3D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Surfaces, Curves and Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Solving Equations of Several Variables . . . . . . . . . . . . . . . . . . . . . . . .
Implicit Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8 Programming Euler

8.1
8.2
8.3
8.4
8.5
8.6
8.7
8.8
8.9

Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Functions and the Matrix Language . . . . . . . . . . . . . . . . . . . . . . . . .
Multiple Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Vector Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Functions as Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Functions and Maxima . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Error messages in Euler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9 Statistics

9.1
9.2
9.3
9.4

Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Statistical Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10 Exact Arithmetic

5
101

101
103
105
107
109

109
113
115
117
119
122
122
125
126
129

129
130
131
133
135

10.1 Exact Scalar Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135


10.2 Guraranteed Inclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
11 Algorithms in Euler

11.1
11.2
11.3
11.4
Index

Di erential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Iteration and Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fast Fourier Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Linear Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

141

141
145
146
148
150

CONTENTS

Preface
This is an introduction to Euler Math Toolbox. The aim of this text is to provide a starting
point in Euler. After reading this text, you should be able to nd your way through Euler
with the help of the documentation and reference.
Euler has been written for math at the University level, designed by a mathematician with the
frequent need for numerical and symbolic computations, and graphical representations of the
results. An additional aim of Euler was to be useful on the school level. The Euler language,
combined with the Algebra system Maxima are ideal tools for this purpose. Tasks of all levels
can be performed with Euler and its programming language. However, Euler is not a simple
click and run system presenting all tools in iconic form. So this introduction might be a big
help.
I wish to thank a lot of friends, users and developers, rst of all my university for giving me the
opportunity to work on this project. Then I thank Eric Bouchare, who ported Euler for Linux.
Currently, I do not have the time to update his version to the level of the Windows version. I
also thank H.D. Gellien for his German handbook. Many users have contributed to Euler with
programs, notebooks and bug hints, especially Alain Busser, Radovan Omorjan and Horst Vogel.
I also thank the developers of Maxima for making their system available for Euler.
Have a good and successful time with Euler.
Rene Grothmann
Eichstatt 2009
http://www.rene-grothmann.de

CONTENTS

Chapter 1

Jumping into Euler


1.1

Computing with Euler and Maxima

In this chapter, I show some simple examples to introduce the main features of Euler and
Maxima. I assume for now that you are able to handle the interface of the program.
With Euler and Maxima, you hold two tools in your hand, one for fast numerical, and the
other for exact symbolic arithmetic. Sometimes it is better to use one tool, and sometimes the
other. Both tools can work together to give you even better answers. By default, the numerical
part of Euler is the main tool and Maxima commands need a special trigger in the command
line. But it is also possible, to use Euler as an interface for Maxima.
Assume you want to do some basic computations with fractions. You get di erent results in
Euler and Maxima.
>1+1/2+1/3+1/4 // compute the fraction with Euler
2.083333333333
>:: 1+1/2+1/3+1/4 // compute the fraction with Maxima
25
-12

The Maxima command is the second command, starting with >::. Maxima experts should use
>:, but >:: is a special compatibility mode of Maxima, so that you can use a syntax more
close to Euler. Euler commands start with a simple prompt >. The Euler result is a decimal
fraction of about 16 digits accuracy. Maxima returns a fractional answer.
However you can print decimal oats as fractions in Euler, and convert fractions to oat in
Maxima.
9

10

CHAPTER 1.

JUMPING INTO EULER

>fracprint(1+1/2+1/3+1/4) // print as fraction in Euler


25/12
>:: float(1+1/2+1/3+1/4) // convert to float in Maxima
2.083333333333334

Why then two programs? Because Maxima is a lot slower than Euler, when it comes to
elaborate numerical stu . Moreover, Euler has some numerical algorithms Maxima does not
have. On the other side, Maxima does a lot of things Euler cannot do. The two programs
complement each other very well.
Let us try some more complex computations in Euler or Maxima. We compute
1000
X1
k=1

in three ways. First in Euler, then as a fraction in Maxima, and nally as a float in Maxima.
In the last command of the following block, Maxima treats 1.0 as a oat, and will do the whole
computation in oating point. The fractional result is not very useful. You might even have
problems to spot the /.
>sum(1/(1:1000))
7.48547086055
>:: sum(1/k,k,1,1000)
533629132822947850455910456240429804096524722803842600971013492484562688\
894971017575060979019850356914090887315504680983784421721178850094643023443265\
660225021002784256328520814055449412104425101426727702947747127089179639677796\
104532246924268664688882815820719848971051107968732493191555293970175089315645\
199760857344730141832840117244122806490743077037366831700558002936592350885893\
60235285852808160759574737836655413175508131522517/712886527466509305316638415\
571427292066835886188589304045200199115432408758111149947644415191387158691171\
781701957525651298026406762100925146587100430513107268626814320019660997486274\
593718834370501543445252373974529896314567498212823695623282379401106880926231\
770886197954079124775455804932647573782992335275179673524804246363805113703433\
121478174685087845348567802188807537324992199567205693202909939089168748767269\
7950931603520000
>:: sum(1.0/k,k,1,1000)
7.485470860550343

Maxima can often compute exact results, where Euler only gives a oating point answer.

1.2.

11

VARIABLES

>sin(45 )
0.7071067811865
>:: sin(%pi/4)
1
------sqrt(2)

The answers are equivalent, but there is no easy way to get the Maxima result in Euler.
Another example is the in nite harmonic series, where Euler can only compute an approximation, but Maxima knows the exact value.
>:: sum(1/k^2,k,1,inf) | simpsum, float(%)
2
%pi
---6

1.644934066848226
>sum(1/(1:1000)^2)
1.643934566682

1.2

Variables

If values or results are needed later, assign them to variables. In the compatibility mode, you
can use := in Euler and Maxima. It is possible to set a variable both in Euler and Maxima
simultaneously.
>a:=2 // variable in Euler
2
>:: a:=2 // variable in Maxima
2
>a::=2 // variable both in Maxima and in Euler
2

12

CHAPTER 1.

JUMPING INTO EULER

To suppress the print of the variable, as well as any print of other results or assignments, use ;.
>:: a:=2; a^3-a
6
>a:=2; a^3-a
6

Note, that variables are separate in Maxima and Euler. The variables set in one part of the
program are not automatically set in the other part. To transfer variables, we use mxmset and
mxmget, or use the ::= assignment
>a:=4; mxmset(a);
>a::=4; // easier
>:: a
4
>mxmget("2*a"),
8

We can get any result from Maxima as a string in Euler, and even evaluate the result immediately
at given values of the variables contained in the expression.
>mxm("diff(x^x,x)")
x^x*(log(x)+1)
>mxmeval("diff(x^x,x)",x=2)
6.77258872224

Even easier is the following syntax, which you might prefer. If a string starts with ::, it is
evaluated by Maxima, and the returned string is the result of the evaluation. Moreover, we can
evaluate any string containing an expression in x at any value of x given in parameter brackets
after the string.

1.2.

13

VARIABLES

>"::diff(x^x,x)"
x^x*(log(x)+1)
>"::diff(x^x,x)"(2)
6.77258872224

So the two worlds of Euler can exchange results very easily.


In Maxima, symbolic variables must not have a value. A variable with a value is always replaced
by the value, and can no longer be used in symbolic computations. To remove a value from a
variable, use remvalue.
>:: a:=4
4
>:: a^2
16
>:: remvalue(a)
[a]
>:: a^2
2
a

To assign a value for just one computation, there are various options. Either append the assignment to the evaluation of the expression. In compatibility mode, this is done with |.
>:: a^2*b | a=4 | b=2
32

Alternatively, use the at function, which can assign a list of values in an expression. at is useful
to use results of solve in other expressions.

14

CHAPTER 1.

JUMPING INTO EULER

>:: at(a^2*b,[a=4,b=2])
32
>:: solve(a*x+b=c,x), at(x^2+2,%)
c - b
[x = -----]
a

2
(c - b)
-------- + 2
2
a

Here, we used % to refer to the result of the previous computation. This should be restricted to
commands in one line. If you need a result in subsequent lines, use variables.
The subst function can replace complete subexpressions.
>:: subst(a^2=16,a^2*b)
16 b

1.3

Discussing Functions

Let us discuss a one-dimensional function. Euler can very nicely cooperate with Maxima for
this purpose. For simple functions, which can be solved analytically, Maxima will be the tool
of choice.
First, we plot the function in Euler. Maxima has a very nice plotting tool too, but Euler is
my choice for plots.
>expr:="log(x)/x";
>plot2d(expr,a=0.1,b=10,c=-3,d=3);

1.3.

15

DISCUSSING FUNCTIONS

Figure 1.1: Plot of log(x)=x

The most elementary form of the plot2d command in Euler can handle a single expression in
x, or the name of a function f(x) de ned in Euler. It can also handle data plots, bar plots,
point plots, curves in the plane, and some more. We set options for this command (like the plot
limits) using assigned parameters.
Storing the function in an expression has the advantage that we can use it more easily, even in
Maxima. Though the variable expr is a variable in Euler, we can use its content in Maxima
with the @expr syntax. We easily nd the maximum of the function, or the in ection point.
>:: solve(diff(@expr,x)=0,x)
[x = %e]
>:: solve(diff(@expr,x,2)=0,x)
3/2
[x = %e
]

There are some utility functions, which use Maxima. mxmdiff will di erentiate, and mxmintegrate
integrate (if possible).
>mxmdiff(expr)
1/x^2-log(x)/x^2
>mxmsolve(mxmdiff(expr)) // all solutions numerically
2.718281828459

16

CHAPTER 1.

JUMPING INTO EULER

>mxmsolve(mxmdiff(expr),n=1) // first solution as string


%e
>mxmintegrate(mxmdiff("x^x"),1,2)
3

mxmsolve

can also nd all zeros of polynomials up to fourth degree as exact expressions.

>x:=mxmsolve("x^2+x",y=1,n=1)
-(sqrt(5)+1)/2
>x:=mxmsolve("x^4+x",y=1) // all complex roots
Column 1 to 1:
-1.220744084606+0i
Column 2 to 2:
0.7244919590005+0i
Column 3 to 3:
0.2481260628026-1.033982060976i
Column 4 to 4:
0.2481260628026+1.033982060976i
>real(x[nonzeros(im(x)~=0)]) // the real roots
-1.220744084606
0.7244919590005

Many exact integrals can be computed with Maxima. Try


Z 1 log(x)
dx:
x2

>:: integrate(log(x)/x^2,x,1,inf)
1

Teachers like to let students produce tables of values. There is a special utility function mxmtable,
which uses Maxima to compute the table. In the following example, we generate a table of the
rst to tenth derivative of xx at x = 1. The variable to be increased is k in this case.
>mxmtable("diffat(x^x,x=1,k)","k",1,10);
1
2
3

1.3.

17

DISCUSSING FUNCTIONS

8
10
54
-42
944
-5112
47160

By default, the mxmtable command will also produce a plot of the values. The numerical output
can be formatted as fractions with the parameter frac=1. However, if Maxima is not needed in
the computation of the table, we can simply use the Euler matrix language, which is discussed
later.
Besides storing expressions in strings, it is possible to de ne functions in Euler and Maxima.
>function f(x) := x^3-x // function in Euler
>:: function f(x) := x^3-x // function in Maxima
3
f(x) := x - x

Again, the two function de nitions are separate. Both worlds can exchange, but not share data.
It might be more exible to set the function in an expression rst, then de ne it in either tool.
We suppress the output of the function de nition in Maxima with the semicolon. In Euler,
this is not necessary.
>expr := "x^3-x";
>function f(x) := @expr // function in Euler
>:: function f(x) := @expr; // function in Maxima
>:: define(f(x),@expr); // alternative form in Maxima
>:: f(x) := @expr; // another form of the function definition

The alternative versions in Maxima have the advantage that the expression is evaluated. The
function declaration will not do this, which may sometimes cause troubles.
Of course, these examples could have been computed by hand easily. So we try a problem, which
involves a lot of computation. The student still has to know how to solve it. But tedious hand
computations can be avoided.

18

CHAPTER 1.

JUMPING INTO EULER

We compute the paraboloid with maximal volume, which ts into a cone. Since this
paraboloid must obviously touch the cone, and we assume it to be symmetric with respect to the
center axis of the cone, we compute the symmetric parabola, which touches the function 1 x
rst.
Example:

>:: function p(x,a,b) := a*x^2+b


2
p(x, a, b) := a x + b
>:: sx := solve(diff(p(x,a,b),x)=-1,x)
1
[x = - ---]
2 a

This is the x value, where the parabola p(x) has derivative 1. Now, we need p(x) = 1
this value.

at

>:: at(p(x,a,b)=1-x,sx), sa:=solve(%,a)


1
1
b + --- = --- + 1
4 a
2 a

1
[a = -------]
4 b - 4

With this knowledge, we de ne the touching parabolas ptb (x). We plot a few of these parabolas
in Euler. To transfer the Maxima function to Euler, we can use the mxm command.
>:: define(pt(x,b),at(p(x,a,b),sa))
2
x
pt(x, b) := ------- + b
4 b - 4

1.3.

19

DISCUSSING FUNCTIONS

Figure 1.2: Touching parabolas

>b:=(0.1:0.1:0.9);
>plot2d("1-abs(x)",r=1); plot2d("::pt(x,b)",add=1);

Now we rotate these parabolas around the y axis and compute the volumes of the paraboloids.
To be able to do this, we need the inverse function, which will be the radius of the cut through
the paraboloid at height y.
>:: solve(y=pt(x,b),x); define(ptinv(y,b),rhs(%[2]))
2
ptinv(y, b) := 2 sqrt(b y - y - b + b)

With this, we can compute the volume, and nally maximize it.
>:: integrate(%pi*ptinv(y,b)^2,y,0,b); define(F(b),%)
3
2
F(b) := - 2 %pi (b - b )
>:: solve(diff(F(b),b)=0,b)
2

20

CHAPTER 1.

JUMPING INTO EULER

[b = -, b = 0]
3
>:: float(F(2/3))
0.93084226773031

The details of this computation, especially the Maxima syntax, are not self evident. For a closer
explanation, have a look into the chapter about Maxima in this introduction.
1.4

Solving Equations

Maxima has the solve command to solve an equation or a system of equations. It is able to

handle most school book examples. To insert the results in subsequent expressions, use at.
>:: sol := solve(x^2-x+1,x)
sqrt(3) %i - 1
sqrt(3) %i + 1
[x = - --------------, x = --------------]
2
2
>:: expand(at(x^2-x+1,sol[2]))
0

Here, we inserted the second solution to the equations. We had to use expand to simplify this
to 0.
However, solve cannot solve all equations, not even all polynomial equations. Then, we have to
be content with numerical solutions. In the following example, we use the bisection method of
Euler to compute a zero, which we can clearly see in the plot.
>plot2d("x^6-10*x+1");
>bisect("x^6-10*x+1",0,1)
0.1000001000006

Euler can also use interval arithmetic to get a close and guaranteed inclusion of the result.
Since the interval Newton method needs the derivative for this, it calls Maxima.

1.4.

21

SOLVING EQUATIONS

>mxminewton("x^6-10*x+1",~0,1~)
~0.10000010000059993,0.10000010000060007~

Systems of equations can be linear or non-linear. Both are handled by Maxima in the same way.
>:: solve([a+b=4,a-2*b=3],[a,b])
11
1
[[a = --, b = -]]
3
3
>:: solve([a*b*c=1,a^2+b^2+c^2=3,a+b+c=3],[a,b,c])
[[a = 1, b = 1, c = 1]]

If there is more than one solution, Maxima delivers a parametric representation. The following
example has three equations with three unknowns, but one equation depends on the other two.
>:: solve([a+2*b+3*c=6,4*a+5*b+6*c=15,7*a+8*b+9*c=24],[a,b,c])

Dependent equations eliminated: (3)


[[a = %r1, b = 3 - 2 %r1, c = %r1]]

Euler has numerical methods to solve equations. Linear systems can be written with a matrix

as Ax = b, and are solved with \. This works for rather large matrices. Let us try the example
above.
>A=[1,1;1,-2]
1
1
>b=[4;3]
4
3
>fracprint(A\b);
11/3
1/3

1
-2

22

CHAPTER 1.

JUMPING INTO EULER

If there is more than one solution, we can use svdsolve, which will yield the closest possible
value (minimizing kAx bk), even if there is no solution at all.
>A=redim(1:9,3,3)
1
4
7
>x=svdsolve(A,[6;15;24])
1
1
1

2
5
8

3
6
9

This is the same solution as in the example above, with the parameter set to 1. To nd all
solutions, we need to understand and compute the kernel of the matrix.
Non-linear systems can often be solved with the Broyden algorithm. We try
xy = 1; x2 + y 2 = 4:
For the Broyden algorithm, we need to de ne a vector valued function rst. The algorithm seeks
the zero of the function.
>function f(v) := [v[1]*v[2]-1,v[1]^2+v[2]^2-4]
>broyden("f",[1,2])
0.517638090205
1.931851652578

In the non-linear example we solved with Maxima above, Broyden will fail, since the Jacobian
of the solution is singular. We can use the very stable Nelder-Mead minimization method in this
case.
>function f(v) := [v[1]*v[2]*v[3]-1,v[1]^2+v[2]^2+v[3]^2-3,v[1]+v[2]+v[3]-3]
>function g(v) := norm(f(v))
>neldermin("g",[0,0,0])
1.00000054821
0.9999996494718
0.9999998023188

Of course, this example can be computed by hand too.

1.5.

1.5

23

VECTORS AND MATRICES

Vectors and Matrices

One of the nest reasons to use Euler is its matrix language. Of course, Euler can compute
linear algebra expressions. But the main advantage is that Euler can use vectors to compute
and hold tables of values.
The basic rule is the following: If any scalar Euler functions is applied to a vector input, it is
evaluated element for element.
>shortformat; v=1:5
1
2
>v^2
1
4
>sqrt(v)
1
1.414214

16

25

1.732051

2.236068

Example: : The following is one way to plot functions. It is the only way, if the vector is
generated elementwise, e.g. by some random process. As an example, we generate a Brownian
motion by adding random numbers. That is, we compute
s[i] := t[1] + : : : + t[i]
for i = 1; : : : ; 1000, where the t[i] are normal distributed values. The function cumsum does just
what we need.

>t:=normal(1,1000); s:=cumsum(t); plot2d(s);

: For another example, we compute a vector of values of the binomial function, and
compute the sum, the mean and the maximal value of the vector.
Example:

>n=0:20; b=bin(20,n); // Compute bin(20,0) ... bin(20,20)


>plot2d(n,b,points=1,title="bin(20,n)"); xlabel("n");
>sum(b), 2^20 // the sum is 2^20
1048576
1048576
>sum(n*b/2^20) // expected value
10
>max(b)
184756

24

CHAPTER 1.

Figure 1.3:

JUMPING INTO EULER

bin(20,n)

All the built-in procedures in Euler apply to matrix input elementwise. If the parameters are
a vector and matrix, the elements are taken in a natural way. E.g., if v is a column vector, and
w is a row vector the A = v  w is the matrix
A[i; j ] = v [i]  w[j ]:

Of course, this is not the matrix product. The matrix product is computed with the dot . in
Euler.
>format(5,0); A=[1,2;3,4]
1
2
3
4
>A*A
1
4
9
16
>A.A
7
10
15
22

Example: : We compute a table of multiplication up to 10. The expression n returns the


transposed vector of n.

1.5.

25

VECTORS AND MATRICES

>n=1:10; A=n*n;
>format(5,0); A,
1
2
3
2
4
6
3
6
9
4
8
12
5
10
15
6
12
18
7
14
21
8
16
24
9
18
27
10
20
30

4
8
12
16
20
24
28
32
36
40

5
10
15
20
25
30
35
40
45
50

6
12
18
24
30
36
42
48
54
60

7
14
21
28
35
42
49
56
63
70

8
16
24
32
40
48
56
64
72
80

9
18
27
36
45
54
63
72
81
90

10
20
30
40
50
60
70
80
90
100

There are functions for recursive sequences. Of course, we could use the programming language
of Euler to generate those sequences. But in this introduction, we restrict ourselves to the
sequence command. The expression for this command can involve a vector x containing the
previous elements of the sequence, and the index n of the new element.
>shortformat;
>sequence("x[n-2]+x[n-1]",[1,1],10) // Compute the Fibonacci sequence
Column 1 to 5:
1
1
2
3
5
Column 6 to 10:
8
13
21
34
55

Another method is to use a loop. Loops outside functions can be used, as long as they t
in one command line. The details of the syntax for loops are explained in the section about
programming.
>v=ones(1,10); for i=3 to 10; v[i]=v[i-1]+v[i-2]; end; v,
Column 1 to 5:
1
1
2
3
Column 6 to 10:
8
13
21
34

5
55

26

CHAPTER 1.

JUMPING INTO EULER

Chapter 2

Introduction
2.1

Overview

Euler Math Toolbox (Euler for short) is a numerical and algebraic software, a mixture between
a computer algebra system (CAS) and a numerical matrix language in the style of Matlab. The
numerical part has been programmed by R. Grothmann, mathematician at the University of
Eichstatt. The algebraic part uses Maxima an open CAS software.
Example: Let us add the following sum
n
X
1 = 3 1 1 
3k 2
3n+1
k=0
rst numerically with Euler for n = 200, and then algebraically with Maxima. The Maxima
result looks a bit di erent from the formula above, but is identical. n = 200 is by far large
enough so that the numerical sum is equal to the limit for n ! 1
The following is an excerpt from an Euler notebook with comments. The command in the
rst line starting with >... is an Euler command. The second line starting with >::... is a
Maxima command.
Numerical summation of 1/3^k, k=0...200
>sum(1/3^(0:200))
1.5
>:: s := sum(1/3^k,k,0,n) | simpsum
- n - 1
3 (3
- 1)
- ---------------2

27

28

CHAPTER 2.

INTRODUCTION

In Maxima we can compute the exact limit for n ! 1.


>:: limit(s,n,inf)
3
2

The numerical kernel of Euler is based on a matrix language. This language can not only
handle simple numbers, but also vectors and matrices of numbers. Moreover, Euler can compute expressions with complex numbers, intervals and strings. All these computations can be
programmed in Euler functions, which might be loaded from external les into Euler. Indeed,
a large part of the Euler syntax is based on functions written in the Euler programming
language.
Euler can also produce graphics, store these graphics in an internal meta format, and output
the graphics for various media, e.g., the graphics window. Graphics can also be imported into
the text window, exported to les or to the clipboard.
The Maxima subsystem communicates with Euler through pipes. It remains a separated
system. However, there are various interactions between Euler and Maxima. This is a mighty
environment to investigate mathematics.
Euler started about 1988. The aim was to get the functionality of Matlab on an Atari ST. The
program was never a clone of Matlab, and went its own path since the beginning. The current
version works on Windows. Older versions for OS/2 or Linux are no longer up to date. However,
Euler will run in Linux under Wine, including Maxima support. A native version for Linux,
based on the native port by Eric Bouchare will have to wait.
2.2

First Steps

From the user viewpoint, Euler looks like a command shell in a text window. Here, commands
can be entered and executed, and the output will appear in the same window below the command.
There is a second window, the graphics window, for the graphical output of Euler. The
current graphics in the graphics window can be inserted into the text window. All commands in
the text window can be edited and executed at any time. It is also possible to add comments.
We refer to the content of the text window as an Euler notebook.
After installing Euler with Maxima, you will nd a shortcut in the start menu and on the
desktop to start the program. Start Euler, and enter the following commands for a rst test.

2.2.

29

FIRST STEPS

Figure 2.1: The text window of Euler

>1+1
2
>exp(-0.5)*sin(3/2*pi)
-0.6065306597126

If you make a mistake, go to the error with the mouse or the cursor keys, and correct the input.
Press return anywhere in the line to start the computation.
For a next step, I suggest opening the introduction notebooks. Use the help menu to nd the
introductions. They should be contained in the Euler installation. After reading a few of these
introduction notebooks, you should have got a very good idea of Euler.
Since Euler uses commands, you should take the time to learn the proper syntax of the program.
This text tries to give you a good start on all aspects of Euler.
Further Information
Help
Open Introduction
Euler Help
Version Information and Update

Menu for help, introduction and demos.


Opens one of the introduction notebooks.
Documentation on Euler.
Look for the current version in the Net.

30
2.3

CHAPTER 2.

INTRODUCTION

The Interface

The interface of Euler is relatively simple with its text window and its graphics window. The
text window has the usual menu, the notebook area and a status line. Both windows can be
enlarged. Euler will remember the sizes and the positions of the windows.

Figure 2.2: Graphics window of Euler

The advantage of such a simple interface is that it is not complicated to learn. The disadvantage
is that it does not o er graphical icons listing all the available commands. However, there is a
reference and extensive help available through the help menu. Moreover, it might be impossible
to squeeze all options of Euler into menus or icons.
There is a special examples menu. It contains short examples for things you might want to do
with Euler. The examples will be inserted into the notebook with comments, and you can edit
them to t your needs.
A reference for the GUI of Euler and a complete reference of all Eulercommands is available
in the documentation. A PDF documentation with all Maxima commands is also among the
numerous help les of Euler.
Have a look into the status line, while you type commands for Euler or Maxima. The
status line will display available commands. Once, an opening bracket is typed for an Euler
function, the status line will display the parameter list and short description of the purpose
of this function or command. Help on Maxima commands is somewhat reduced, but still all
available. All Maxima commands starting with the current string will appear in the status line.
The graphics window contains the current graphics. It can be resized. To get a square aspect
ratio, there is a menu item to resize the graphics window accordingly. The content of the

2.4.

31

THE COMMAND LINE

graphics window can be exported in various formats. Either use the menu, or the functions
savepng, savesvg, saveps.
Further Information
TAB key

2.4

Switches between test and graphics window.

The Command Line

All commands are entered into the text window in the current command line. The commands
are in dark red and start with the prompt > for Euler, and >:: or >: for Maxima. The user
cannot delete the prompt >. Furthermore, the text window may contain comments in green color,
and function de nitions in blue color starting with $. Colors are not shown in this introduction.
Enter commands just like in any other program. Use the arrow keys or the mouse to move the
cursor. The Ctrl key together with the cursor moves the cursor word by word. Have a look into
the edit menu for more options. Press the enter key anywhere in a line to execute the command.
Command lines can be deleted. The deleted lines are accumulated and can be inserted anywhere.
The shortcuts for this are listed in the edit menu.
To stop a long computation press the Esc key. This will also interrupt the print of long vectors.
To add a comment to a command line, start the comment editor with F5. Simple, one line
comments can be appended to the command line using //.
>sum(1:1000) // computes the sum from 1 to 1000
500500

If an expression is too long for one command line, or does not look well in one single line, it can
be broken into the next line with ..
>a:=1;
>b:=(1+a+a^2+a^3)* ..
>(1+2a+3a^2)
24
>plot2d("x^y",a=0,b=3,c=0,d=3, ...
> niveau=-10:0.1:10, ...
> title="x^y");

32

CHAPTER 2.

INTRODUCTION

If lines end with three dots ... Euler will execute the complete command at once (muli-line
commands). This will work, even if the cursor is in the second line of the multi-line command.
You can mark text in the text window by dragging the mouse over it. The cursor will remain
in the current command line at the current position.
Marked text can be copied to the clipboard. The copied text can then be inserted into the
current command line, if it is less than one line, or in front of the current command line, if it
contains several lines. This is also a quick way to send Euler commands by mail. Of course, it
might be better to send the notebook le.
There are special menu entries to copy commands only, or to copy a formatted version of the
notebook. Copying commands only is designed to generate an Euler le from the marked commands. It will note contain the output. Formatted copying is good for generating documentation
les for Euler. The output can still be pasted back to Euler.
Further Information
,
;
Home, End
Shift key

2.5

Separates the commands in one line.


. Separates the commands and suppresses output.
Moves the cursor to the line ends.
Marks text with the cursor keys.

Syntax

Euler distinguishes commands, expressions and assignments.


>list sin // command
*** Functions:
antialiasing arsinh asin isinterval sin sinh
7 items found!
>a:=sin(pi/2) // assignment
1

is a command to nd all functions or commands containing the string.


The most elementary expressions are mathematical expressions. Euler will evaluate these expressions with the usual order of evaluation.
list

>(1+2*4)*(3+4)/(4+2)
10.5

2.6.

33

NOTEBOOKS

There are functions which work like commands. The result of these functions is of no interest. In
this case, you can prevent the output of the result with ;. An example is the plot2d command,
which returns the coordinates of the current plot window.
>plot2d("x^2",-1,1);

An assignment contains a variable name on the left side, and an expression on the right side of
:=. Here, the semicolon ; will often be used to suppress the output.
>a:=2;
>a:=a^2;
>a
4
>a:=a^2;
>a
16

Euler does also understand the syntax a=2 for assignments. However, in cases like a=a^2 this

looks confusing, so it is no longer recommended. In this introduction, we use the := syntax.


There are also multiple assignments to assign multiple return values of functions to several
variables. Read more about this in the section about programming.
Further Information
> x^2
>:: x^2
>> x^2
2^2^2
Ctrl-Cursor up

2.6

Sends the command to Euler.


Sends the command to Maxima.
Sends the command to Yacas.
Evaluates to 2^(2^2).
Calls an old command from the command history.

Notebooks

The content of the text window is called a notebook. Notebooks can be saved in a simple text
format, or exported to HTML for web pages or printing. Notebooks can contain commands,
Euler output, comments, and images. If a notebook containing images is saved, the images are
saved in separate les in the PNG format.
To navigate through the commands in a notebook use the mouse or the cursor keys. The
comments and the output of a command belong to the command. To edit the comment of a

34

CHAPTER 2.

INTRODUCTION

Figure 2.3: Colors in a notebook

command, use the comment editor with F5. The output cannot be edited. Command lines can
be inserted and deleted only together with their comments and their output.
Note that the order of execution may not be the order of the commands in the notebook. Entering
the commands in the following notebook yields the output printed here. If you go back to the
second line and execute it once more, a = 4 will be used, and the output changes to 16.
>a:=2;
>a*a
4
>a:=4;

To run all commands in a notebook use the correspondig menu entry. All variables will be set
in the correct order then. For a clean start, re-load the current notebook via the list of recent
notebooks. By default, Euler will restart automatically, when a new notebook is loaded.
Saved notebooks should have the extension *.en. These les are ordinary text les. However,
it is not recommended to edit notebooks with an external text editor. The encoding of the
notebooks is the current encoding of the system the notebook was saved with.
Images will be saved in separate les in PNG (portable network graphics) format, and are referred
from the notebook le by le name.
By default, Euler performs a fresh restart when a notebook is loaded. This can be disabled
with a switch in the options menu. A restart a ects Maxima too. The Maxima process ends,
and starts again.

2.7.

HELP AND DOCUMENTATION

35

Figure 2.4: Editing comments

Further Information
Open Notebook
Open User Notebook
Open Introduction
Print Graphics

2.7

Open notebooks in the current directory.


Open notebooks in the user directory.
Open notebooks in the program directory.
Directly print the current graphics window.

Help and Documentation

Euler comes with a complete reference in English, a reference to the Euler interface, quick

tips, demos, examples, and this documentation. Use the help menu, the examples menu and the
three menus with Euler Maxima and user commands to access these items. The user command
menu is empty, until you load an Euler le containing menu items.
The examples in the menu will paste into the notebook, including a comment and several commands. The commands in the menus for Euler and Maxima will be pasted at the current cursor
position. The commands can contain places to be lled in. These places look like ?explanation
with an explanation about the expected item. Place the cursor in front of the question mark
and start typing to ll the item. You can go to the next question mark with the cursor key to
the right.
Also observe the status line in the text window while typing a function. After the open bracket
of the function, you can nd a list of parameters and an explanation there.
Moreover, there is the help command. The help lines may include examples and a reference to
a demo le. To call the examples directly, use the example command.

36

CHAPTER 2.

INTRODUCTION

>list sin
*** Commands:
*** Euler functions:
antialiasing arsinh asin isinterval sin sinh
>help sin
sin is a builtin function.
abs,sin,cos,tan,asin,acos,atan,exp,log,sign,sqrt
Mathematical functions. Work for real, complex and interval scalars
and matrices.
The trigonometric functions work for radians.
To convert use x or deg(x). (use shift-F7 for  )
Examples :
sin(45 ) // -> 0.7071067811865 - sin in degrees!
sin(pi/2) // -> 1
sin(rad(90)) // -> 1
...
cos(1)^2+sin(1)^2 // -> 1
cos(acos(0.1)) // -> 0.1
plot2d("cos(x)",0,2pi);
...

Above you see the help for a built-in function. Functions in the Euler language look a little bit
di erent.
>help sinh
function sinh ()
Function in file : functions
...

There is a similar command for Maxima functions.


>mxmhelp

plotdf

2.8.

37

EULER FILES

-- Function: plotdf (<dydx>, ...options...)


-- Function: plotdf (<dvdu>, [<u>,<v>], ...options...)
-- Function: plotdf ([<dxdt>,<dydt>], ...options...)
-- Function: plotdf ([<dudt>,<dvdt>], [<u>,<v>], ...options...)
Displays a direction field in two dimensions <x> and <y>.
<dydx>, <dxdt> and <dydt> are expressions that depend on <x> and
<y>. <dvdu>, <dudt> and <dvdt> are expressions that depend on <u>
and <v>. In addition to those two variables, the expressions can
...

Further Information
list text
help text
type text

2.8

Find all functions and commands containing the text.


Prints help for a function or command.
Types the content of a function or a variable.

Euler Files

If you want to develop longer and more complicated programs, it becomes useful to put all
function de nitions and all commands into external Euler files. These les should have the
extension *.e, and can be loaded into Euler with the load command.
Files in the current directory will be found using the name alone. The current directory is the
directory, where the current notebook is loaded from or saved to. Otherwise, use the full path
the le, or include the directory of the le into the Euler path.
>load sound
Save and load WAV sound files. Analyze frequencies.
...

Some Euler les start with comments, which are printed in the text window. This can be
switched o with ;.
>load sound;

38

CHAPTER 2.

INTRODUCTION

This kind of comment in the Euler le must be written between comment and endcomment.
There are other ways to comment an Euler le.
Here is an example of an Euler le.
comment
This text is shown when the file loads.
endcomment
/*
Multi-line comment
Some variables:
*/
g:=9.81; // earth gravitational acceleration
t:=2.5; // time
s:=1/2*g*t^2; // height
// Output of s:
s,

Save this le into a le named test.e, and load it with the load command as follows
>load test
This text is shown when the file loads.
30.65625

Euler les can be edited with the internal or an external editor. To call the internal editor, use

the menu item, or press F9. A dialog will open. If the editor is called in a line which starts with
a load command, it uses this le.

>load "file"

If the line starts with a function command, it will edit the function. After editing the function,
a missing endfunction will be added. Moreover, the function line will be closed with ... so
that the function de nition can be interpreted with one stroke of the return key.

2.8.

39

EULER FILES

>function f(x) ...


$ // function body
$endfunction
>

The editor edits the le EulerTemp.e in the user directory, if it is started in an empty line.
However, other les can be loaded into the editor, or the editor le can be saved to some other
le.
On any other line the editor will edit the current line. Even multi-line commands ending with
... can be edited this way.
All output of the load command will be printed at the current command line. The commands
in the Euler le are not inserted into the current notebook.

Figure 2.5: Con guration of the external editor

The external editor works with the load command too. But it cannot edit function de nitions,
or command lines. The default external editor is JE, a Java based editor, which is installed
with Euler. However, you can con gure any other editor of your choice. Euler does not wait for
the external editor to nish. You can leave the editor open, switch to Euler, and run the load
command there. Do not forget to save any changes.

40

CHAPTER 2.

INTRODUCTION

Chapter 3

Expressions and Plots


3.1

Elementary Expressions

Of course, Euler knows all elementary mathematical operations, and evaluates expressions
following the usual conventions. Nevertheless, sometimes you should use brackets to avoid errors.
>-2^2
-4
>2^-2
0.25
>2^3^4
2.417851639229e+024
>(2^3)^4
4096

The list of available functions and operators is quite long. Note, that the natural logarithm
can be computed with log or ln, There is also the decimal logarithm log10. The square root
function is called sqrt.
Expressions can produce an error messages. E.g., the square root of negative numbers does not
exist, unless we convert the number to a complex number.
>1/0
error in :
1/0
^
>sqrt(-1)

41

42

CHAPTER 3.

EXPRESSIONS AND PLOTS

Error in sqrt
error in :
sqrt(-1)
^
>sqrt(complex(-1))
0+1i

It is possible to switch the error messages o . In that case, the result is NAN (not a number). The
plot2d command uses this feature, so that the user does not have to care about the de nition
set of the plotted function.
>errors off; 1/0, errors on;
1.#QNAN
>plot2d("x^x",-1,1); // x^x is not defined for negative x

Powers with integer exponents are well de ned, even for negative numbers. Other powers of
negative numbers are not de ned.
>(-2)^3
-8
>0^0
1
>(-1)^(1/2)
Illegal argument for ^
Error in ^
error in :
(-1)^(1/2)
^

For very large or small numbers, use the exponential format.


2.4e20 = 2:4  1020
2.4e-20 = 2:4  10 20
>1.2e10
12000000000
>1.2e-10
1.2e-010

3.2.

43

ACCURACY

Euler knows some other data types, but it handles integers and booleans as reals. The result

of a boolean expression is 0 for false and 1 for true. Besides the obvious comparison operators,
Euler uses != or <> for not equal. Note that equality is checked with ==. There es a special
operator =, which checks for equality up to the constant epsilon. The boolean \and" is &&,
and the boolean \or" is ||. Moreover, in condition for if statements or and and can be used.
>1<=2, 2<=1
1
0
>1==2 || 2==2
1
>1+epsilon~=1
1

Further Information
2**3
help sin
help round

Open Demos

3.2

Alternative for 2^3.


Help for sin etc.
Rounding etc.
Examples and demos.

Accuracy

Euler uses IEEE oating point numbers with about 16 decimal digits. To see this, we evaluate

the sine function in , after we have increased the number of digits in the output. In the default
format, small numbers are rounded towards 0.
>longestformat; sin(pi)
1.2246467991473532e-016

The output can be tuned in many ways. The most important formats are the oating point
formats of various lengths, and the fractional format. Some formats can be used for just one
output with a print command.
>longformat; 1/3
0.3333333333333
>longestformat; 1/3
0.33333333333333331

44

CHAPTER 3.

EXPRESSIONS AND PLOTS

>shortformat; 1/3
0.333333
>fracformat; 1/3
1/3
>longformat;
>fracprint(1/3)
1/3

There are some special formats, and even user de ned formats. In the following example we use
a very narrow format.
>format(5,0); 1:10, longformat;
1
2
3
4
5
6

10

Note that some formats print row vectors and scalar numbers in a dense way. This is controlled
with the command denseformat(n), where n is the number of spaces between the elements.
longestformat, and the general format command set denseformat(0), which prevents the
dense output.
>longformat; 1:10 // dense output (the default)
1 2 3 4 5 6 7 8 9 10
>format(10,5); 1:6
1.00000
2.00000
3.00000
4.00000
5.00000
>longestformat; 1:6
Column 1 to 3:
1
2
Column 4 to 6:
4
5

6.00000

3
6

The internal representation of a number can be printed with printhex. The following example
shows that 0:1 is not exactly representable in a dual computer.
>printhex(0.1)
1.1001100110011001100110011001100110011001100110011010*2^-4
>longestformat; (0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1)-1
-1.1102230246251565e-016

3.3.

45

VARIABLES

If more accuracy than 16 digits is needed, Euler o ers a long accumulator and exact arithmetic.
More on this later. Moreover, Maxima has a long arithmetic.
To round a number use round, and to get the integer or fractional part use floor.
>round(pi,2)
3.14
>floor(pi)
3

Comparisons of real numbers deliver a boolean result, represented in Euler by 1 or 0. The


comparison ~= tests for equality up to an internal accuracy epsilon. == tests for exact equality.
>1/3+2/3 == 1
1
>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 ~= 1
1

Further Information
demos format
degformat(flag)
degprint(x)
: 2^1000
epsilon
a =b

3.3

Many examples for formats.


Print in degrees.
Print x in degrees.
\In nite" arithmetic in Maxima.
Returns the internal epsilon.
a about equal to b.

Variables

Results can be stored in variables for later use. To assign a value to a variable, Euler has :=
and =. We prefer :=, since an assignment like a=a^2 looks confusing.
>g:=9.81; t:=2.5; s:=1/2*g*t^2;
>s
30.65625

Euler, as well as Maxima, can refer to the previous result with %. This should only be used

within a single line.

46

CHAPTER 3.

EXPRESSIONS AND PLOTS

>solve("cos(x)-x",1), cos(%)-%
0.7390851332152
0

Variables are cleared, when Euler is restarted, or with the clear varname function (or with
remvalue(varname)).
Euler variables do not have a type. They can take data of any type. However, the type can be
checked with typeof, or the functions isreal, iscomplex etc. To check for a matrix, use size.
>isreal(1:10)
1
>iscomplex(I)
1
>length(2)
1
>length(1:10)
10
>length(random(3,2))
3

To list all variables, use listvar. To list only the variables with a speci c name use listvar
string. Many variables are prede ned and should not be changed.
>listvar
Epsilon
ResetEpsilon
ResetView
...

Type: Real
Type: Real
Type: Real Matrix (1x4)

The constants I, E and pi look like variables, but are functions without parameters. There also
variants of this constants like i% and e% for Maxima.
When multiplying constants with variables, the multiplication sign * can often be omitted. In
this case, multiplication binds stronger than division. This feature is useful for units (see below).
This is di erent from the convention, that there should be a space between the number and the
unit.

3.4.

47

UNITS

>a:=4; 3a+4a^2
76
>3/4a, 3/4*a
0.1875
3
>36km$/2h$ // 36 km in 2 h are 5 m/s
5

Further Information
clear var

3.4

Clears a variable.

Units

Variables in Euler do not have a unit. We assume that physical numbers are in meter, kg and
seconds etc. (the so called IS system). To convert to other units, multiply the number with the
unit. Do not add a space before the unit. To convert back, divide by the unit. All units end
with a dollar sign to avoid confusion with other short variable names.
Example: In this example we convert 90 km/h to m/s and back.
>90km$/h$
25
>25/(km$/h$)
90

For another example, we compute the potential energy of a body with 100 kg in
10 m height in Joule. From that, we get the speed it hits the ground in km/h. The gravity
constant at sea level is contained in the constant g$.
Example:

>Epot:=g$*100kg$*10m$
9806.65
>sqrt(2*Epot/100kg$)/(km$/h$)
50.41709710009

The explicit units kg$ and m$ are unnecessary. These constants are 1.

48

CHAPTER 3.

Example:

EXPRESSIONS AND PLOTS

How many minutes takes the light from sun to earth on average.

>AU$/c$/min$
8.316746396769

To print a number in a speci ed format with units use print. Alternatively, append the string
to the number. For special formats, there is also prinf, which uses the format conventions of
the computer language C.
>print(1/3,10,2,"km/h")
0.33333km/h
>0.25|" J"
0.25 J
>printf("%10.2fkm/h",1/3)
0.33km/h

Further Information
help UnitsInEuler

3.5

Lists all units in Euler.

2D Plots

Discussing a function is a common task in mathematics. For a start, we explain simple plots
here, as well as simple tasks like computing the zeros, the extrema and the integral of a function
numerically. For exact symbolic solutions, refer to the chapter about Maxima.
The easiest way to plot a function in Euler is to use strings. Strings in Euler are enclosed in
double quotes. The string must contain an expression in the variable x. Other variables must
be de ned globally.
>a:=2; b:=3;
>plot2d("a+b*x+x^2",-3,3);

This example produced the graphics in 3.1. The graphics window will only be displayed for a
short time. As soon as Euler produces text, the text window will become the top window. To
switch to the graphics window or back, press the TAB key.

3.5.

49

2D PLOTS

Figure 3.1: Simple plot of a function

Plots with expressions or functions can also be interactive, using the parameter user=1. Then
the user can press the cursor keys to move the plot window, or the + or - key to zoom in or out.
The space bar resets to the default view. Pressing return ends the plot.
>plot2d("a+b*x+x^2",a=-3,b=3,user=1);

Another method is to use wait. This commands waits for a speci c time, or until the user
presses any key.
>plot2d("a+b*x+x^2",-3,3); wait(60);

Of course, it is also possible to specify the plot range exactly. For this, set the parameter
a,b,c,d, or the parameter r. plot2d has many more parameters. In the following examples, we
change the color and thickness of lines. Moreover, we add one plot to another using the add=1
parameter.
>plot2d("x^2",a=-2,b=2,c=0,d=4,thickness=2);
>plot2d("1+2*(x-1)",add=1,thickness=2,color=4);

r=...

will specify a rectangular area for the plot. square=1 enforces a square plot area.

50

CHAPTER 3.

EXPRESSIONS AND PLOTS

Figure 3.2: Parabola and Tangent

>plot2d("sin(x)/x",r=8);
>plot2d("x^3-x",a=0,b=1,square=1);

The content of the graphics window can be embedded into the text window with insimg. See
the example in Figure 3.3. The parameter to insimg is the height of the graphics in text lines,
25 by default. Embedded graphics are saved with notebooks as PNG les, and linked to in the
HTML export. They can either be saved in the same directory as the notebook or the web page,
or in a sub-directory images.
Example: The following code plots the sinc function and its tangent in 1. We use Maxima to
compute the tangent.
>plot2d("sin(x)/x",r=pi);
>plot2d("::sin(1)+diffat(sin(x)/x,x=1)*(x-1)",add=1,color=4);

The plot2d function can plot point clouds, distribution of data in bar plot form, and a lot more.
Some of these plots are discussed in later chapters of this introduction. For a complete overview
use

3.6.

51

NUMERICAL ANALYSIS

Figure 3.3: Graphics in the text window

>help plot2d

or read the HTML version of this text in the reference.


Further Information
style="-"
title="..."

3.6

line style (".", "--")


title line.

Numerical Analysis

There
p are many functions in2 Euler, which accept expressions. The following example computes
2 as zero of the function x 2 using the stable bisection method and the faster secant method.
>bisect("x^x-2",1,2)
1.559610469462
>secant("x^x-2",1,2)
1.559610469462

52

CHAPTER 3.

EXPRESSIONS AND PLOTS

The target value is 0 by default, but it can also be speci ed as y.


>secant("x^x",1,2,y=2)
1.559610469462

A simple form of the Secant method is used by solve, which needs only one starting value.
>solve("cos(x)-x",1)
0.7390851332152

The even faster Newton method needs a derivative. We can use Maxima to compute this derivative for us. The function mxmnewton calls Maxima automatically to compute the derivative.
>newton("x^2-2","2x",1)
1.414213562373
>expr="x^2-2"; newton(expr,"::diff(@expr,x)",1)
1.414213562373
>mxmnewton("x^2-2",1)
1.414213562373

Euler has functions for numerical integration and di erentiation. To integrate, either use the

robust and fast Gau integration, or the exact Romberg method. Of course, the very stable
Simpson method is also available. The Gau method is exact up to polynomials of degree 19,
and uses only 10 evaluations of the function. Moreover, the interval can be subdivided into a
number of subintervals to increase the accuracy.
>gauss("x^19",0,1)
0.05
>gauss("exp(-x^2/2)/sqrt(2pi)",-20,20,20)
1
>gauss("x^x",1,2)
2.050446234535
>romberg("x^x",1,2)
2.050446234535
>simpson("x^x",1,2)
2.050446235955

3.6.

53

NUMERICAL ANALYSIS

The basic function integrate uses an adaptive integration, and nds many integrals.
>integrate("1/sqrt(pi)*exp(-x^2)",-5,5)
1

Often Maxima can compute an exact form of the integral.


>romberg("x*exp(x)",-1,1)
0.7357588823429
>mxmeval("integrate(x*exp(x),x,-1,1)")
0.7357588823429

In principle, numerical di erentiation is not very accurate. Maxima should be used for di erentiation.
>diff("x^20/20",1)
1.00008493834
>"::diff(x^20,x)"
20*x^19
>mxmeval("diff(x^20/20,x)",x=1)
1

To nd extrema of a function use fmin or fmax. There is also a function fextrema, delivering
two values, a list of minima, and a list of maxima.
>fmin("x^3-x",0,1)
0.5773502652516
>fmax("x^3-x",-1,0)
-0.5773502727191
>{xmin,xmax}:=fextrema("x^3-x",-1,1); xmin, xmax,
0.5773502652494
-0.5773502721866

Further Information
mxm
mxmeval

Computes the expression with Maxima.


Evaluates the return value from Maxima in Euler.

54
3.7

CHAPTER 3.

EXPRESSIONS AND PLOTS

Definition of Functions

Since there will be a later chapter on programming in Euler, you will nd here the basics only.
To program very simple functions, there are one line functions in Euler.
>function f(x) := 1/(x^2+1)
>f(2)
0.2
>plot2d("f",-3,3,r=5);

Most Euler functions, which accept expressions, also accept functions. Simply pass the function
by name contained in a string.
Functions can have more than one variable, or use global variables. It is possible to set default
values for parameters, or use a variable number of arguments. Moreover, a variable in a function
can be de ned in the list of arguments when the function is called. Those variables are called
assigned parameters.
>function f(x) := a*x^2+x+1
>a:=4; f(1) // use the global a
6
>f(1,a=2) // set a locally
4
>function g(x,a) := a*x^2+x+1
>g(1,4) // now a is a parameter to g
6
>function h(x,a=4) := a*x^2+x+1
>h(1) // use the default for a
6
>h(1,0) // use another value for a
2

A problem arises, if plot2d is used to plot a function with more than one parameter, and we
cannot use a global variable. plot2d can handle this by passing additional parameters to the
function to be plotted. Those parameters are appended after a semicolon ;. We call them
semicolon parameters.
>function f(x,a) := exp(-x^2)*sin(a*x)
>plot2d("f",0,10;9); // with a=9

3.7.

55

DEFINITION OF FUNCTIONS

There is the rule that additional assigned parameters like the plot range must be give after the
semicolon parameters.
>plot2d("f";6,r=3); // with a=6

Example:

Let us compute the zero of x2

a for the variable a using the bisection method.

>function f(x,a) := x^2-a


>bisect("f",1,2;3) // use a=3 in f
1.73205080757

More complex Euler functions can be de ned using the full syntax of the function command.
This is necessary for functions using control statements. Those function start with function,
and end with endfunction. Simply enter the function line by line, and press the Esc key to end
the de nition.
>function f(x)
$ if x>0 then return x
$ else return x^2
$ endif
$endfunction
>f(-2), f(2),
4
2

The notebook will be in a special function input state when a function is entered. This is
natural, since lines in a function must be entered one by one. You can no longer go up or down
with the cursor keys. To exit this state, use the endfunction or the Esc key.
However, it is easier to use the internal editor to edit such a function in the notebook. Press F9
in the function line to start this editor. endfunction will be added, if it is missing. Moreover,
the function line will end with ... so that the function can be interpreted with one stroke of
the return key.
Note, that if must end with endif. return ends the function and returns the value. If it
is missing, an empty string is returned. For other control structures, see the chapter about
programming.

56

CHAPTER 3.

EXPRESSIONS AND PLOTS

Figure 3.4: Visibility vs. distance in m

Let us compute the distance of the horizon depending on the height of the viewer,
and solve a converse problem with the secant method.
Example:

>function horizon(h) := sqrt(2*rEarth$*h+h^2)


>shortformat; horizon(30)/km$
19.5296
>plot2d("horizon(x)/km$",0,1000,title="Distance of Horizon");
>xlabel("Height (m)"); ylabel("Distance (km)");
>secant("horizon(x)",0,100,y=80km$)
503.381

To make a function of any expression in x, there is a special trick. If the expression is stored in
the string variable str, the syntax @str will be replaced with the content of the expression.
>expr := "x^3-x";
>function f(x) := @expr
>type f
function f (x)
useglobal; return x^3-x
endfunction
>f(2)
6

We have used type to make the function de nition visible. It does indeed contain the correct
expression.

3.7.

DEFINITION OF FUNCTIONS

57

Moreover, it is possible to evaluate an expression directly, just as any function.


>expr := "x^3-x";
>expr(2)
6

In this case, the parameters are assigned to the variables x,y,z in this order. Additional parameters can be assigned using assigned parameters.
>expr := "a*x*y";
>expr(2,3,a=-1)
-6

For more complex functions, refer to the chapter about programming in Euler.

58

CHAPTER 3.

EXPRESSIONS AND PLOTS

Chapter 4

Maxima
4.1

Direct Input of Maxima Commands

Maxima is an algebraic, symbolic system, which can be called from Euler. After the rst call,
Euler will start an instance of Maxima in the background, and communicate with it through
pipes. By default, Maxima starts, whenever a new notebook is loaded, or Euler is restarted.
There is a global switch to start Maxima later, when it is rst used. Alternatively, start Maxima

with the command mxmstart and stop it with mxmstop.


There are two ways to use Maxima, the direct input of commands, and via strings. In this
section, we use the direct method. To send a command to Maxima use the prompt >:: or the
prompt >: in front of the command.
The preferred method is the compatibility mode with the prompt >::. In this mode, Euler
will do a lot of formatting to the command. Instead of the Maxima command separation, you
can use the Euler defaults , and ;. The Maxima assignment to variables is replaced by the
default in Euler :=. Maxima functions can be written with function ....
The direct mode with the >: prompt still does a little bit of editing. You can add comments
with // just like in Euler commands. Moreover, you need not nish the command with $ or ;,
since Euler will add ; if it is missing.
The Maxima output is printed to the Euler notebook just like Euler output. The output
numbers of Maxima are removed by default, since they make no sense in a notebook environment. Use variables to hold values instead. Only within the same line, use % to refer to the
previous result.
>:: (a+b)^2/(a-b)
2

59

60

CHAPTER 4.

MAXIMA

(b + a)
-------a - b
>:: expand((a+b)^5) // expand a product
5
b

4
+ 5 a b

2
+ 10 a

3
b

3
+ 10 a

2
b

4
+ 5 a

5
b + a

>:: factor(a^2+2*a*b+b^2) // factor a product


2
(b + a)

As you see, Maxima uses symbolic variables. Symbolic variables must not have a value. The
value of a variable can be removed with the Maxima command remvalue(variable).
If you want to use Euler as a Maxima interface primarily, you can switch to Maxima mode.
The command maximamode will toggle the compatibility mode by default. For more control use
maximamode on or maximamode direct. There is also a menu option to start Euler in one of
the Maxima modes whenever it starts. In Maxima mode, euler ... will send a command to
the Euler sub-system.
>maximamode on
Maxima mode is on (compatibility mode)
>1/3
1
3
>euler 1/3
0.3333333333333
>maximamode off
Maxima mode is off

Maxima uses an \in nite" arithmetic for integers and fractions. It will keep all digits of a

computation. Floating point numbers are only used on speci c request.


>:: 1+1/3+1/7

4.1.

DIRECT INPUT OF MAXIMA COMMANDS

61

31
-21
>:: 100!/(50!*50!)
100891344545564193334812497256

The last example works in Euler too, but larger factorials cause an over ow in Euler.
>100!/(50!*50!)
1.008913445456e+029

For the binomial function, Euler can use the function bin, which uses a di erent algorithm,
and works for large numbers. Moreover it is very much faster than any method in Maxima.
The function float converts a Maxima expression to the same type of oating numbers as in
Euler.
>:: float(1000!/(500!*500!)) // convert to IEEE floating point
2.7028824094543655E+299
>bin(1000,500) // Euler function for binomials
2.702882409454e+299

There is also a oating point arithmetic with an adjustable number of digits in Maxima. To use
it, we have to assign the number of digits to the variable fpprec ( oating point precision).
>:: fpprec:=40; bfloat(sqrt(2))
1.41421356237309504880168872420969807857b0

In compatibility mode (prompt >::), variables in Maxima are assigned with a :=. To separate
commands with printing in the compatibility mode, use a comma as in Euler, and to separate
without printing, use a semicolon ;.

62

CHAPTER 4.

MAXIMA

>:: expr := expand((1+x)^5);


>:: factor(expr)
5
(x + 1)
>:: expr := expr*expr, factor(expr)
5
4
3
2
2
(x + 5 x + 10 x + 10 x + 5 x + 1)
10
(x + 1)

If a Maxima expression is too long for one line, it can be spread over many lines. Use ... just
as in Euler.
>:: expand((1+x+x^2+x^3) * ...
>::
(1-x))
4
1 - x

Some Maxima functions can be appended to an expressions, and work like ags for the evaluation
function. E.g., expand can be used this way. Also, various simpli cation hints can be given, like
ratsimp, which simpli es rational expressions. For most of these ags, there is also a function
version, which might be preferred.
>:: (x+4)^2/((x+4)*(x+3)) | expand, % | ratsimp
2
x
8 x
16
------------- + ------------- + ------------2
2
2
x + 7 x + 12
x + 7 x + 12
x + 7 x + 12

x + 4
----x + 3

4.2.

DIFFERENTIATION AND INTEGRATION

63

>:: log(16)/log(2) | radcan


4

Trigonometric simpli cation with trigsimp does not work as a ag, and needs to be used as a
function. In general, it is safer to use such commands as functions.
>:: sin(x)^2+cos(x)^2, trigsimp(%)
2
2
sin (x) + cos (x)

1
>:: trigreduce(sin(x)^3)
3 sin(x) - sin(3 x)
------------------4

4.2

Differentiation and Integration

Calculus is a typical application for symbolic computations. Maxima can compute the derivative
of all its functions, and knows also most integrals.
>:: diff(x^5,x)
4
5 x
>:: diff(x^5,x,2) // second derivative
3
20 x
>:: integrate(x^5,x)
6
x

64

CHAPTER 4.

MAXIMA

-6
>:: integrate(2/(x+1),x,1,2)
2 (log(3) - log(2))

Of course, we can also compute the anti-derivative rst, and then insert the limits. Use at to
evaluate an expression at some values.
>:: s := integrate(t/(1+t^2),t)
2
log(t + 1)
----------2
>:: at(s,t=b)-at(s,t=a)
2
2
log(b + 1)
log(a + 1)
----------- - ----------2
2

In connection with some integrals, Maxima may ask questions to the user.
>:: integrate(x^n,x)
Is

n + 1

zero or nonzero?

>:: nonzero
n + 1
x
-----n + 1

To avoid this, it is possible to set assumptions for the variables.

4.3.

65

MAXIMA FUNCTIONS

>:: assume(n>0); integrate(x^n,x,0,1)


1
----n + 1
>:: forget(n>0); // remove the assumption

Maxima uses functions either as verbs or nouns. The di erence is, that verbs evaluate, and
nouns do not. To enter di erential equations, we must use the di erentiation diff as a noun.
To do this, we use the diff form.
>:: eq := diff(y,x) = y + x^2
dy
2
-- = y + x
dx
>:: ode2(eq,y,x)
2
- x
x
y = ((- x - 2 x - 2) %e
+ %c) %e

Further Information
x^2 | x:2
subst(x^2=a,x^2+y^2)

4.3

Evaluates x2 at x = 2 (does not work for diff).


Substitution of sub-expressions.

Maxima Functions

In Maxima we can de ne one line functions just like in Euler. The keyword function is
necessary in compatibility mode to prevent the evaluation of the function body before the function de nition. In some cases, the function body should be evaluated. Just omit the function
keyword in these cases.
>:: function f(x) := 1/(x^2+1)
1
f(x) := -----2

66

CHAPTER 4.

MAXIMA

+ 1

>:: f(2)
1
5
>:: diff(x^x,x); df(x) := % // evaluate the function body %

This simple de nition without function evaluates the function expression in compatibility mode.
Alternatively, use define, which evaluates the function expression always.
>:: assume(x>0); g(x) := integrate(t/(1+t^2),t,0,x)
2
log(x + 1)
g(x) := ----------2
>:: g(1)
log(2)
-----2

Check this numerically with Euler.


>romberg("x/(1+x^2)",0,1), log(2)/2
0.34657359028
0.34657359028

The compatibility mode simply adds to evaluate the expression. Conversely, stops the
evaluation of the expression, which is sometimes useful, e.g., when de ning di erential equations.
>:: diff(x^x,x)
d
x
-- (x )
dx

4.3.

67

MAXIMA FUNCTIONS

To set a function in Euler and Maxima simultaneously, use ::=.


>function f(x) ::= exp(x)*x^2
>plot2d("f",-1,1); // Use Euler
>:: diff(f(x),x) // Use Maxima
2
x
x
x %e + 2 x %e

Figure 4.1: f (x) and g(x) in [0; 5]

The solve command of Maxima nds exact solutions for expressions in one or more
variables. We wish to nd the area between two functions.
Example:

>:: function f(x) := (2*x^3-9*x^2+2)/3


3
2
2 x - 9 x + 2
f(x) := --------------3
>:: function g(x) := 5/3*x+2/3
5
2
g(x) := - x + 3
3

68

CHAPTER 4.

MAXIMA

>:: solve(f(x)=g(x),x)
1
[x = - -, x = 5, x = 0]
2
>:: integrate(g(x)-f(x),x,0,5)
125
--3

4.4

Exchanging Values between Maxima and Euler

Sending direct commands to Maxima keeps the results of Euler and Maxima separated from
each other. Moreover, the output of Maxima is in a 3D format, which cannot be cut and paste
to Euler. Note, that variables in Maxima and in Euler are separated from each other.
A simple way to set variables for both worlds with one command is the "::=" assignment. This
works for strings, numbers and short matrices. For long matrices, use the mxmset command
explained below.
>a::=3;
>expr::="x^x";
>v::=1:10;

Euler provides methods to exchange results between Euler and Maxima. The most simple
method is the function mxm, which evaluates a string in Maxima and delivers the result in a
string for Euler. A shortcut is to precede the string with :: or @:. This string can be used
like any other expression in Euler.
>expr:="::diff(x^x,x)"
x^x*(log(x)+1)
>plot2d(expr,0.1,2);
>newton("x^x-2",expr,2) // Newton needs the derivative
1.559610469462
>expr(2) // evaluate an expression in x
6.77258872224

4.4.

EXCHANGING VALUES BETWEEN MAXIMA AND EULER

69

To evaluate the string immediately with global variables, use @:string, or the syntax for the
evaluation of an expression in x in Euler.
>x:=2; @:"diff(x^x,x)"
6.77258872224
>"::diff(x^x,x)"(2)
6.77258872224

Some Euler functions use Maxima in the background. E.g., mxmnewton computes the derivative
of the function for the Newton method.
>mxmnewton("x^x-2",2) // Solve x^x=2
1.559610469462

To evaluate a string in Euler we can use the Euler function evaluate. This function uses
global variables only, or variables de ned in the function containing evaluate. To simplify
evaluation in connection with Maxima, the function mxmeval passes a string to Maxima, and
evaluates the result using speci ed variables.
>mxmeval("diff(x^x,x)",x=2) // evaluating a Maxima result
6.77258872224
>expr:="::diff(x^x,x)"; // the same
>x:=2; evaluate(expr) // in two steps
6.77258872224
>expr(2) // shortcut
6.77258872224

How to use an Euler expression in Maxima without de ning it as a variable in Maxima? The
necessary string manipulations are done automatically with the syntax @str. This syntax pastes
the content of the string variable str into the command. By the way, this syntax not only works
in Maxima commands, but also in the de nition of Euler functions.
>expr:="x^2";
>:: diff(@expr,x)
2 x

70

CHAPTER 4.

MAXIMA

>":: define(f(x),@expr)"; mxmeval("f(2)")


4

Another practical method is to use Maxima functions in Euler. We can get an expression in
x for Euler, even if we used a di erent variable name in Maxima. Note that we use mxm to
evaluate a complete function de nition in Maxima.
>"::assume(a>0)"; "::define(f(a),integrate(t/(1+t^2),t,0,a))";
>"::f(x)"
log(x^2+1)/2
>"::f(x)"(1)
0.34657359028
>plot2d("::f(x)",0,1);

Note that calling mxmeval is not very fast. For time critical applications, it is better to de ne
the function in Euler. This is very easily done by calling Maxima at compile time. In the
de nition of an Euler function, use @:"..." to evaluate the string in Maxima, and paste the
result into the Euler function.
>function f(x) := @:"diff(x^x,x)"
>type f
function f (x)
useglobal; return x^x*(log(x)+1)
endfunction

The internal de nition of the function f can be printed with type (more on this in the section
about programming). As you see, the function contains the correct expression for the derivative
of xx.
If the string result of Maxima should remain a string, use the following syntax.
>function test(a,b) := romberg("@:diff(x^x,x),x",a,b)
>type test
function test (a,b)
useglobal; return romberg("x^x*(log(x)+1)",a,b)
endfunction
>test(1,2)
3

4.5.

71

MATRICES IN MAXIMA

To set variables in Maxima directly in Euler, we can use mxmset. This will set a variable with
the same name and value in Maxima. The converse is mxmget, which is almost identical to
mxmeval.
>A:=[1,2;3,4];
>mxmset(A); // set the variable A in Maxima
>B:=mxmget("invert(A)") // compute the inverse with Maxima
-2
1
1.5
-0.5
>A.B
1
0
0
1
>mxmset("x",2); mxmget("x^2")
4

As noted above ::= is a simple way to set a variable both in Maxima and in Euler.
>A::=[1,2;3,4];

4.5

Matrices in Maxima

As the last example of the previous section shows, Maxima can also handle matrices. The simple
Euler syntax with semicolons and commas cannot be used to de ne matrices, however. Instead,
there is the matrix command in Maxima, and also in Euler.
>:: A := matrix([1,2],[4,5])
[ 1
[
[ 4

2 ]
]
5 ]

>:: determinant(A)
- 3
>:: charpoly(A,t)
(1 - t) (5 - t) - 83

72

CHAPTER 4.

MAXIMA

>:: invert(A) | detout


[ 5
- 2 ]
[
]
[ - 4
1 ]
- -----------3
>:: invert(A).A
[ 1
[
[ 0

0 ]
]
1 ]

To transport a matrix from Maxima to Euler, we use mxmget.


>fracprint(mxmget("invert(A)"));
-5/3
4/3

2/3
-1/3

Often Maxima uses vectors to collect results, such as solutions of equations. These simple row
vectors are called lists. To use the results of solve in Euler we need to remove the x=...
part in the solutions. In the following example we map rhs (right hand side) to the list. As an
example, we compute the rather complicated zeros of a cubic polynomial and evaluate the result
in Euler. Two of the zeros are complex values.
>:: sol := solve(x^2-3*x+1=0,x)
sqrt(5) - 3
sqrt(5) + 3
[x = - -----------, x = -----------]
2
2
>:: map(rhs,sol)
sqrt(5) - 3 sqrt(5) + 3
[- -----------, -----------]
2
2
>:: sol := solve(x^3+x^2+5*x+4=0,x);
>mxmeval("map(rhs,sol)")
Column 1 to 1:

4.5.

73

MATRICES IN MAXIMA

-0.08804641337601-2.201627508452i
Column 2 to 2:
-0.08804641337601+2.201627508452i
Column 3 to 3:
-0.823907173248+0i

As an example, we nd all Pythagorean triples a2 + b2 = c2. For this, we choose to


numbers 2 < q < p without a common divisor and solve the equation
p
x:
x2 + y 2 = 1; y = 1
q
Example:

The simple idea is to set

a
b
x= ; y=
c
c

which yields a2 + b2 = c2. E ectively, we compute the intersections of a line with the unit circle.
Since one intersection is rational the other must be rational too.
>:: solve([x^2+y^2=1,y=1-x*p/q],[x,y])
2
2
2 p q
q - p
[[x = -------, y = -------], [x = 0, y = 1]]
2
2
2
2
q + p
q + p

Maxima returns a list with two pairs of solutions for x and y. We use at to set x and y to these

solutions.

>:: x := at(x,sol[1]), y := at(y,sol[1]),


2 p q
------2
2
q + p

2
2
q - p
------2
2
q + p

74

CHAPTER 4.

MAXIMA

>:: x^2+y^2 | ratsimp


1

The solution is

a = 2pq; b = q 2

p2 ; c = q 2 + p2 :

This is a famous formula for the Pythagorean triples.


4.6

Compatibility and Direct Mode

If you wish to study one of the various introductions to Maxima you will have to use the direct
mode, and the original Maxima syntax. To enter a command in this mode, start the command
with >:... or use the direct Maxima mode with maximamode direct. Note that the mxm
command in Euler uses the direct syntax too. This makes no di erence, since it is used for
simple expressions anyway.
To use the direct mode, you have to enable it in the options menu.
The translation between direct and compatibility mode is rather straightforward. We collect the
di erences of the compatibility mode and the direct mode in the following list.
Further Information
>::...
>:...
, and ;
; and $
|
,
:=
:

Command for Maxima in compatibility mode


Command for Maxima in direct mode
Separation of commands in compatibility mode
Separation of commands in direct mode
Append options in compatibility mode
Append options in direct mode
Set variables compatibility mode
Set variables in direct mode

The main di erences are the command and option separators. The following are two lines of
code with the same meaning.
>:: diff(x^2/(1+x^2),x); %|factor,
2 x
--------2
2
(x + 1)

4.6.

COMPATIBILITY AND DIRECT MODE

75

>: diff(x^2/(1+x^2),x)$ %,factor;


2 x
--------2
2
(x + 1)

Variables are set di erently too. The direct mode uses : and the compatibility mode uses :=
just as Euler does.
>: a:3$ a^2
9
>:: a:=3; a^2
9

For the de nition of a function, the direct mode uses either :=, which does not evaluate the
function body, or define, which does. Alternatively, the evaluation can be forced with (...)
>: f(x) := integrate(x^2,x)
2
f(x) := integrate(x , x)
>: f(x) := (integrate(x^2,x))
3
x
f(x) := -3
>: integrate(x^2,x)$ f(x) := %
f(x) := %
>: integrate(x^2,x)$ define(f(x),%)
3
x
f(x) := -3

76

CHAPTER 4.

MAXIMA

As you see, the simple := can lead to very wrong answers. In the compatibility mode, we use the
Euler form function ... to set a function, which does not evaluate the body, and f(x):=...
to evaluate the function body. This is logical, since := works in the same way for variables.
>:: integrate(x^2,x); f(x) := %
3
x
f(x) := -3
>:: function f(x) := integrate(x^2,x)
2
f(x) := integrate(x , x)

Chapter 5

Data Types
5.1

Complex Numbers

So far we have used oating point real numbers most of the time. Euler has two other numerical
data types, which can be used in matrices: complex numbers and intervals. In this section, we
introduce complex numbers.
Complex numbers are entered by appending i to the imaginary part, or using the constant I,
which has the aliases %i and I$.
All computations in Euler are real, as long as there are no other data types involved. Thus
sqrt(-1) will not work. To turn a real number x into a complex number, use complex(x). For
the converse, use real(z). This will yield an error message if the imaginary part of z is not close
to zero. Of course, re(z) and im(z) simply compute the real and imaginary part of a complex
number.
>1+2i
1+2i
>(1+2*I)^2
-3+4i
>real(I*I)
-1
>sqrt(complex(-1))
0+1i
>re(2+3i), im(2+3i)
2
3

Note that sqrt(complex(-1)) is not exactly I. But the usual format rounds the result to the
expected value. To stop this, use longformat, or zerorounding(0).
77

78

CHAPTER 5.

DATA TYPES

Euler can compute most numerical functions in the complex range. The results of the logarithm

and the power function use the main part, with the complex plane cut along the negative axis.
>real(exp(I*Pi))
-1
>sqrt(-1+0.1i), sqrt(-1-0.1i)
0.049937771837+1.001246114128i
0.049937771837-1.001246114128i
>real(sin(I)^2+cos(I)^2)
1
>log(complex(-1))
0+3.14159265359i

It is also possible to plot complex numbers. See the section about the Euler matrix language
for an example.
Further Information
abs(z)
arg(z)
conj(z)
plot2d

5.2

Modulus
Argument in ] ;  ]
Complex conjugate z
Knows how to plot complex grids and curves.

Intervals

The third data type in Euler is intervals. Interval arithmetic is used to control rounding errors.
Euler can produce guaranteed inclusions of solutions for many problems using its interval
arithmetic.
Intervals are entered using the ~a,b~ notation as in the following examples. ~x~ creates a small
interval around x.
>~1,2~
~1,2~
>interval(1,2)
~1,2~
>left(~-1,2~), right(~-1,2~), middle(~-1,2~)
-1
2
0.5
>~1~
~0.99999999999999978,1.000000000000000

5.2.

79

INTERVALS

Alternatively, the engineering notation  can be used. This special character is not on the
keyboard, and can be entered using the function key F8.
>10.1
~0.9,1.1~

The basic rule of interval arithmetic is that the result includes all values from any of the
parameter intervals. Thus x*x and x^2 can yield di erent results. x*x multiplies any value in x
with any other value in x, while x^2 takes the square of any value in x.
>~0.9,1.1~+~0.9,1.1~
~1.8,2.2~
>2*~0.9,1.1~
~1.8,2.2~
>~-1,1~*~-1,1~
~-1,1~
>~-1,1~^2
~0,1~

The same is true for functions. The function is evaluated in all elements of the parameter interval,
and the result is an interval containing all results. But due to eciency, often this interval is
not the smallest interval containing all results.
>sin(~1,2~)
~0.71,1~
>left(sin(~1,2~)), sin(1), sin(2)
0.7121263857702
0.8414709848079
0.9092974268257

Note that the sine function has a maximum in the interval. The closest inclusion would be
[sin(1); 1].
Sometimes, the function mxmieval delivers better results. However, it uses Maxima to compute
the derivative of the function. In mxmieval it is possible to subdivide the interval for even better
results.

80

CHAPTER 5.

DATA TYPES

>z:=~0.1,0.5~; z^3+z^2-2*z
~-0.99,0.18~
>mxmieval("x^3+x^2-2*x",~0.1,0.5~)
~-0.84,-0.12~
>mxmieval("x^3+x^2-2*x",~0.1,0.5~,10)
~-0.63,-0.18~

We measure the angle of a tower in 100 m distance as 11:25 above ground. How
high is the tower? All measurement have only the given accuracy. So we use proper intervals to
estimate the result. For comparison, we use a pseudo-exact computation.

Example:

>sin(11.25 0.005 )*(1001)


>sin(11.25 )*100
19.50903220161

Example:

~19.3,19.8~

The error of the Simpson formula with step size h = (b


h4
(4)
180 sup jf (x)j

a)=n can be estimated by

x2[a;b]

We use that to get a guaranteed inclusion for the integral in Euler.


>n:=100; a:=0; b:=1; h:=(b-a)/(2*n);
>res:=simpson("exp(-x^2)",0,1,n)
0.7468241328175
>res+~-1,1~*h^4/180*mxmeval("diff(exp(-x^2),x,4)",x=~0,1~)
~0.74682413266,0.74682413297~
>romberg("exp(-x^2)",0,1)
0.746824132814

For the Simpson method, the fourth derivative is needed. We use Maxima to compute it.
Finally, we can also use the function mxmiint to get a very narrow inclusion for the integral
using Maxima and even higher derivatives.
>mxmiint("exp(-x^2)",0,1)
~0.746824132812408,0.746824132812446~

5.3.

81

STRINGS

Further Information
a && b
a || b
a << b
a <<= b
expand(a,f)
mxminewtion etc.

5.3

Intersection of intervals
Interval containing the union of intervals
Tests, if a is contained in b
The same, where equality is allowed
Expands a by the factor f
See the chapter about exact arithmetic

Strings

Strings are the non-numerical data type in Euler. They are used for le input and output, and
to hold expressions. Many functions accept expressions, as we have already seen. Strings are
also used to communicate with Maxima. Strings can form vectors, but not matrices.
Here are some examples of string functions.
>s:="This is a test",
This is a test
>strlen(s)
14
>ascii(s) // first character in a
84
>char(84)
T
>substring(s,6,8)
is
>substring(s,-4,-1)
test
>substring(s,strfind(s,"a",0),-1)
a test
>"affe"<="bravo"
1
>s|" "|s
This is a test This is a test

There are also vectors of strings. plot2d uses these vectors to plot more than one expression.
>plot2d(["sin(x)","cos(x)"],0,2pi);

For interactive programs, there is the input function. The input is interpreted as a numerical
expression. If there is an error, Euler will prompt the user again, until the expression is valid
or the user presses the Esc key.

82

CHAPTER 5.

DATA TYPES

The following commands should be entered into an Euler le. To do this, press
F9 in an empty line to open the internal editor, and copy and paste the following text into the
editor.

Example:

"Prim factors.",
n=input("Enter a number: ");
"Factors:", factor(n),

If this le is loaded, we get the following dialog between the user and Euler.
Prim factors.
Enter a number: ? >34243127
Factors:
31
773

1429

Further Information
strfind
tolower
toupper

5.4

Finds substrings
Converts to lower case
Converts to upper case

Polynomials

Polynomials are not a primitive data type. They are stored in Euler as vectors of coecients
starting with the constant coecient. Euler can evaluate, add, multiply, divide, and di erentiate polynomials. Here are some examples compared to Maxima.
>p:=[1,2,3]; polyval(p,2)
17
>pd:=polydif(p); polyval(pd,2)
14
>mxmeval("diff(1+2*x+3*x^2,x)",x=2)
14
>p2:=polymult(p,p)
1
4
>"::expand((1+2*x+3*x^2)^2)"
9*x^4+12*x^3+10*x^2+4*x+1
>"::expand((1+2*x+3*x^2)^2)"(2)

10

12

5.4.

83

POLYNOMIALS

289
>polyval(p2,2)
289

The zeros of polynomials can be computed in Euler using a numerical method. Euler nds
all complex zeros. Here is a comparison with Maxima.
>polysolve(p)
-0.333333-0.471405i
>:: sol := solve(1+2*x+3*x^2=0,x)

-0.333333+0.471405i

sqrt(2) %i + 1
sqrt(2) i - 1
[x = - --------------, x = --------------]
3
3
>mxmeval("map(rhs,sol)")
-0.333333-0.471405i

-0.333333+0.471405i

Further Information
polydiv(p,q)
polytrunc
polyadd
polycons

Divides with remainder (multiple returns!)


Minimizes the degree of the polynomial
Adds polynomials
Generates a polynomial from its zeros

84

CHAPTER 5.

DATA TYPES

Chapter 6

Euler Matrix Language


6.1

Matrices and Vectors

A matrix in Euler is entered using brackets [...]. The values of each row are separated by
commas, the rows are separated by semicolons. Incomplete rows are lled with zeros.
>[1,2;3,4]
1
3
>shortformat; a:=3;
>[1,a;0,1,a;0,0,1,a]
1
0
0

2
4

3
1
0

0
3
1

0
0
3

A vector is simply a matrix with one row or column. The transposition of a matrix is indicated
by A.
>A:=[1,2;3,4;5,6]
1
3
5
>A
1
2

2
4
6
3
4

5
6

85

86

CHAPTER 6.

EULER MATRIX LANGUAGE

One of the most important ways to generate matrices is the : operator. It can have a step value,
or the default step value 1. By numerical reasons, adding the steps will not always exactly meet
the nal value. Euler uses the internal epsilon to check for this.
>matrix([1,2],[3,4])
1
3
>0:0.1:1
0 0.1 0.2 0.3 0.4
>1:3
1 2 3
>sum(1:1000)
500500

2
4
0.5

0.6

0.7

0.8

0.9

There are many functions generating a complete matrix. Here are some examples.
>zeros(2,2)
0
0
>ones(1,5)
1 1 1 1
>id(2)

0
0

1
0
0
1
>A=2*id(3); setdiag(A,1,[-1,-1])
2
-1
0
2
0
0

0
-1
2

Matrices can also be appended to each other, horizontally or vertically.


>v:=1:3
1 2 3
>v|v
1 2 3
>v_v

1
1

2
2

3
3

1
1

2
1

3
1

>v_1

6.1.

87

MATRICES AND VECTORS

To access a single matrix element, or a submatrix, Euler uses brackets as in A[i,j]. Round
brackets are supported, but deprecated by default. Omitting the column index returns a line
of A, unless A is a row vector. Always remember, that Euler matrices start with the index 1.
A[0] yields an empty matrix, or an error message depending on a global ag!
If the indices are vectors, we get a submatrix. The indices may even be unordered. In this
case, we get a permutation of the rows or columns. All rows or columns are addressed with :.
Negative indices count from the end of the matrix. Here are some examples.
>v:=[1,2,3,4,5]
1 2 3 4 5
>v[4]
4
>v[-1]
5
>v[3:5]
3 4 5
>A=[1,2,3;4,5,6;7,8,9]
1
4
7
>A[1,3]
3
>A[1]
1 2 3
>A[1:2,1:2]
1
4
>A[:,2]
2
5
8
>A[[2,1],3]
6
3

2
5
8

3
6
9

2
5

It is possible to assign values to a submatrix. Take care that the values must t into the
submatrix. It is also possible to assign a single number to a submatrix. In this case, all elements
of the submatrix will be set to this number.
>format(10,5); v:=1:5, v[2:3]:=0
1
0
0
>A:=v_v
1
0
0

88

CHAPTER 6.

1
0
0
>A[[1,2],[2,3]]:=[8,9;10,11]
1
8
9
1
10
11

4
4

5
5

EULER MATRIX LANGUAGE

Note, that submatrix indexing can also be applied to the result of functions, if the result is of
matrix type. E.g., the shuffle function shues vectors randomly, and we can extract the rst
6 values with index 1:6.
>sort(shuffle(1:49)[1:6])
27
28
32
44
45
48

Further Information
linspace(a,b,n)
equispace(a,b,n)
size(A)
cols(A)
rows(A)
diag(A,k)
redim(A,n,m

6.2

n equidistant points in [a; b]


points distributed in arcsine distribution
The size [c,r] of A
Number of columns of A
Number of rows of A
k-th diagonal of A
Reformat A into a new matrix

The Matrix Language

The basic rule of the matrix language is that all functions and operators are evaluated element
for element (elementwise operation). So the multiplication  is not the matrix multiplication,
but the elementwise multiplication. The matrix multiplication uses a dot as in A.B.
>v:=[1,2,3]; v*v
1
>sqrt([1,2;3,4])
1
1.73205

4
1.41421
2

6.2.

89

THE MATRIX LANGUAGE

An alternative, which does also work in Maxima is the matrix command.


>matrix([1,2],[3,4])
1
3

2
4

When combining a matrix with a vector in one operation, Euler tries to bring the vector to the
same size as the matrix by duplicating lines or columns in a natural way, so that the result can
be computed element for element. A row vector and a column vector will combine to a matrix.
Moreover, using a scalar number and a matrix in one operation will combine the scalar number
with all elements of the matrix.
>v:=[1,2,3]; 2*v+4*v
6
>w:=[1;-1;0]
1
-1
0
>v*w
1
-1
0

12

18

2
-2
0

3
-3
0

In the last example above, the resulting matrix A has the property that
ai;j = vj  wi :
Euler uses the elements from the rows of w and the columns of v to form the matrix. Imagine
v duplicated three times vertically, and w appended three times horizontally. Of course, this is
not the matrix product!
The same rule applies to all operations, also for comparisons like >, which deliver 1 or 0 elementwise.
Example: The Pascal triangle is usually written
1
1
1
1
2
1 :
1
3
3
1
Since we do not have triangle matrices in Euler, we use a square matrix, lled with 0. This is
very easy to achieve, since bin(n,m) follows the matrix rules, and moreover delivers 0, if m < 0
or m > n.

90

format(7,0); n:=0:5; bin(n,n)


1
1
1
1
0
1
2
3
0
0
1
3
0
0
0
1
0
0
0
0
0
0
0
0

CHAPTER 6.

1
4
6
4
1
0

EULER MATRIX LANGUAGE

1
5
10
10
5
1

Figure 6.1: The function xn

We already plotted functions using expressions. However, it is also possible to plot


a table of values.
Example:

>x:=-1:0.01:1; y:=x^3; plot2d(x,y);


>n:=(1:5); plot2d(x,x^n);

The second example works, since n is a column vector. Thus xn is the matrix
0x
1
B
.
@.

1
.. C
A:

: : : xm

x51 : : : x5m

The function plot2d plots every row of the matrix as a separate function, using the same x-values
for all rows.

6.2.

91

THE MATRIX LANGUAGE

Example:

We compute the Gau algorithm for


x+y+z =1
2x + z = 2
x y=1

by hand.
>fracformat(10);
>A:=[1,1,1;2,0,1;1,-1,0]; b:=[1;2;1];
1
1
1
2
0
1
1
-1
0
>M[2]:=M[2]-2*M[1]; M[3]:=M[3]-M[1]
1
1
1
0
-2
-1
0
-2
-1
>M[2]:=M[2]/(-2); M[3]:=0
1
1
1
0
1
1/2
0
0
0
>M[1]:=M[1]-M[2]
1
0
1/2
0
1
1/2
0
0
0

The result reads as

M:=A|b
1
2
1
1
0
0
1
0
0
1
0
0

x1 = 1

x3 =2; x2 = x3 =2;

where x3 is arbitrary.
Example: Here is an example in the complex plane. The following code generates complex
numbers z evenly spaced around the unit circle (roots of unity). Then we map these numbers
with z 7! z2 + z, and plot the those values. The function plot2d knows how to plot a path of
complex values.
>x:=linspace(0,2*pi,1000); z:=exp(I*x);
>plot2d(z+z^2,r=2);

We could also plot a grid of complex numbers.

92

CHAPTER 6.

EULER MATRIX LANGUAGE

Figure 6.2: Image of the unit circle with w = z 2 + z

>x:=-1:0.1:1; y:=x; z:=x+1i*y;


>plot2d(exp(z));

Example:

How many prime numbers are less than n? And which of them have the form m2 +1?

>n:=1000; k:=3:2:n; sum(isprime(k))+1


168
>nonzeros(isprime(k) && k==floor(sqrt(k))^2+1)*2+1
5 17 37 101 197 257 401 577 677

Further Information
max(A),min(A)
totalmax(A),totalmin(A)
extrema(A)
sort(v)

6.3

Maximum and minimum of the rows of A


Maximum of all values in A
Maximum and minimum plus the indices
Sorts v

Linear Algebra

For the multiplication of matrices we use the dot A.x. Thus v.w is the scalar product
between column vectors. The cross product is computed with crossproduct.

6.3.

93

LINEAR ALGEBRA

>v:=[1;2;3]
1
2
3
>v.v
14
>crossproduct(v,[1;1;2])
1
1
-1

The inverse matrix can be computed with inv(A). Note that A^(-1) would deliver the inverses of the elements of A. By the same reason, the matrix powers have to be computed with
matrixpower(A,n).
>shortformat; A:=[1,2;2,1]
1
2
2
1
>det(A)
-3
>fracprint(inv(A));
-1/3
2/3
2/3
-1/3
>matrixpower(A,-5).matrixpower(A,5)
1
0
0
1

Of course, the last example does not deliver the identity matrix exactly. The default output
format rounds this, however.
To solve a linear system, use the backslash operator.
>A:=[2,2,2;1,2,2;1,1,2]
2
1
1
>b:=A.[1;1;1]
6
5
4

2
2
1

2
2
2

94

CHAPTER 6.

EULER MATRIX LANGUAGE

>A\b
1
1
1

Note, that this is more ecient then inv(A).b. If A is not regular (numerically det A = 0), you
will get an error message.
Further Information
kernel(A)
svdkernel(A)
image(A)
svdimage(A)
rank(A)
lu(A)

6.4

Kernel of A
Orthogonal basis of the kernel
Image of A
Orthogonal basis of the image
Rank of A
LU decomposition of A (See help lu)

Regression Analysis

If a system Ax = b has no solution, we can try to minimize the norm kAx bk using the function
. This is always necessary if there are more equations than unknowns.

fit

>shortformat; A:=[1,1;2,1;3,1]
1
1
2
1
3
1
>b:=[2;3;2]
2
3
2
>x:=fit(A,b)
0
2.333333
>norm(A.x-b)
0.8164966

uses Givens rotations. The alternative is to use fitnormal, which uses the normal equation.
It fails, if A does not have maximal rank. The function svdsolve uses a more complicated
method involving singular values. As an advantage, svdsolve delivers the result with minimal
norm, if there is more than one result.
fit

6.4.

95

REGRESSION ANALYSIS

>shortformat; A:=[1,2,3;4,5,6;7,8,9]
1
2
4
5
7
8
>det(A)
0
>b:=A.ones(3,1)
6
15
24
>svdsolve(A,b)
1
1
1

3
6
9

There is the function polyfit to t polynomials of a given degree to given data.


Example: Let us t a polynomial of degree 2 to the exponential function on [ 1; 1]. The error
is circa 0.07.
>x:=-1:0.1:1; y:=exp(x); p:=polyfit(x,y,2)
0.995583
1.11404
0.540186
>plot2d("exp(x)-polyval(p,x)",-1,1)
-1
1
-0.053854

0.0684755

In this example we t functions of the form


f (x) = ae x + be 2x + c
to measurements
(x1; y1 ); : : : ; (xn ; yn):
We generate the measurements arti cially adding random errors to a given function. The matrix
for the t contains the basis functions evaluated at the points of measurement.
0 e x1 e 2x1 11
B
... ... C
@ ...
A:
x
2
x
n
n
e
e
1
Such a matrix can be generated very easily using the matrix language of Euler.

Example:

96

CHAPTER 6.

EULER MATRIX LANGUAGE

>function f(x,a,b,c) := a*exp(-x)+b*exp(-2*x)+c


>x:=0:0.1:1; y:=f(x,1,0.8,0.5)+normal(size(x))*0.01;
>A:=f(x,1,0,0)|f(x,0,1,0)|f(x,0,0,1);
>s:=fit(A,y)
0.993416
0.80455
0.498895
>plot2d(x,y,points=1);
>plot2d(x,(A.s),add=1);

Finally, we plot the data and the t.

Figure 6.3: A best t

6.5

Eigenvalues and Singular Values

are computed with eigenvalues, eigenvectors with eigenspace. Of course, we


can also compute the characteristic polynomial, and its zeros using polysolve.
In the following example, we compute the eigenvector with the function kernel. The eigenvalues
will always be complex. However, we can convert to real, since our matrix is known to have real
eigenvalues.

Eigenvalues

>shortformat; A:=[1,2;2,1]
1
2

6.5.

EIGENVALUES AND SINGULAR VALUES

97

2
1
>shortformat; A:=[1,2;2,1]
1
2
2
1
>charpoly(A)
-3 -2 1
>real(polysolve(charpoly(A)))
-1 3
>l:=re(eigenvalues(A))
-1 3
>eigenspace(A,-1)
-0.7071068
0.7071068
>v:=kernel(A-l[2]*id(2))
1
1
>A.v
3
3
>{l,M}:=eigen(A); re(l)
-1 3
>re(M.A.inv(M))
-1
0
0
3

The function eigen returns two values, a vector with the eigenvalues, and a matrix M of eigenvectors. It is known that
MAM 1 = D:
If A is symmetric, Euler delivers an orthogonal M , and we have M 1 = M 0 .
Singular Values compute a decomposition of an n  m matrix A in the form
A = UDW 0 :
The n columns of U will be orthonormal. D is a m  m diagonal matrix, and W is orthogonal.
>A:=[1,2,3;4,5,6]
1
2
4
5
>{U,d,W}:=svd(A);
>d
9.508032 0.7728696 0
>U
-0.3863177
-0.9223658
-0.9223658
0.3863177

3
6

0
0

98

CHAPTER 6.

EULER MATRIX LANGUAGE

>U.U
1
0

0
1

>W.W
1
0
0
>U.diag(3,3,0,d).W
1
4

0
1
0

0
0
1

2
5

3
6

Further Information
xeigenvalue(A,l)
jacobi(A)

6.6

Tries to improve the eigenvalue l numerically.


Jacobi method for symmetric A

Sparse Matrices

Euler has support for sparse matrices. This is a special data type, which only saves the non-zero
indices of a matrix. There are functions to handle or modify space matrices, and to convert to
and from ordinary matrices.
The function cpx compresses a matrix into the internal compressed mode. The function determines zero entries using the internal epsilon. to convert back to ordinary matrices, use decpx.
>A=id(6)*2+diag(6,6,-1,1)+diag(6,6,1,1); fracprint(A)
2
1
0
0
0
1
2
1
0
0
0
1
2
1
0
0
0
1
2
1
0
0
0
1
2
0
0
0
0
1
>R=cpx(A)
Compressed 6x6 matrix
1
1
2
1
2
1
2
1
1
2
2
2
2
3
1
3
2
1
3
3
2
3
4
1
4
3
1
4
4
2

0
0
0
0
1
2

6.6.

99

SPARSE MATRICES

4
5
5
5
6
6

5
4
5
6
5
6

1
1
2
1
1
2

Compressed matrices can be multiplied rapidly. The following would take much longer using the
usual multiplication.
>n=1000; A=id(n)*2+diag(n,n,-1,1)+diag(n,n,1,1);
>R=cpx(A);
>R2=cpxmult(R,R);

Example: In the following example we build a random sparse matrix, and set b in Ax = b equal
to the sums of the rows. To get such a matrix, we use cpxset, which takes rows of the form
(i; j; ai;j ). To make sure the matrix is regular, we set the diagonal to a large value 20.
Then we solve the linear system, using the conjugate gradient method for large, sparse systems,
as implemented in the function cpxfit.

>H=cpxzeros(1000,1000);
>ind=intrandom(10000,2,1000);
>H=cpxset(H,ind|normal(rows(ind),1));
>H=cpxsetdiag(H,0,20);
>b=cpxsum(R);
>x=cpxfit(R,b);
>totalmax(cpxmult(R,x)-b)
0

Sparse matrices appear as incidence matrices of graphs. The function rectangleIncidenceX


creates the incidence matrix of a rectangle graph. For a ner adjustment, there are functions to
set rows of the matrix to values, or to multiply rows by numbers, and to set elements to speci c
values.

100

CHAPTER 6.

EULER MATRIX LANGUAGE

Chapter 7

Functions of Several Variables


7.1

3D Plots

Figure 7.1: The function f (x; y) = xy

Just as plot2d plots functions in one variable, the function plot3d handles functions of two
variables. Euler can draw the graph of these functions in a vanishing line projection.
Plots of functions are scaled by default to t into the unit cube with the default scale=1.
Moreover, the function values are scaled to agree with the x-y-range. To avoid this use fscale=0,
or set the scaling to some other maximal function value.
Here are some examples.
101

102

CHAPTER 7.

FUNCTIONS OF SEVERAL VARIABLES

>plot3d("x*y");
>plot3d("x*y",user=1);
>plot3d("x^2+y^2",xmin=0,xmax=4,ymin=0,ymax=4, ...
> hue=1,light=[1,1,0],fscale=4);
>plot3d("x^2+y^2",rmax=2,polar=1);
>plot3d("x^2+y^3",wire=1,anaglyph=1);
>plot3d("sin(x^2+y^2)",rmax=4,polar=1,frame=0,n=100,scale=1.5);
>function f(x,y) := 1/max(1,x^2+y^2))
>plot3d("f",polar=1,r=3);

There are the following basic types of 3D plots in Euler.


. These plots show the surface, and a grid on the surface. There is a backside
and a frontside with di erent colors. The parameter hue=1 adds shading instead of a
simple color, and removes the grid. The shading is computed with respect to the direction
of a light source (default is light=[0.5,0.5,1]) and ambient light (default is amb=0.1).
Parameters can be three functions in x and y for the the three coordinates of the surface,
or three matrices.
 3D function plots. The most basic type of solid plots, showing the graph of a function.
plot3d needs only one function in x and y.
 3D grid plots. The surface is not shown, only the grid. This can be achieved using the
parameter wire=1.
 3D line plots. This is a sequence of line segments in 3D. Use the parameter wire=1.
The function needs either three parameter functions in x, or three matrices, at least one
of which is a row vector.
 3D point plots. This plots a cloud of points in space. The function needs three vectors
for the coordinates of the points. Set points=1.


Solid plots

Figure 7.2: Anaglyph plot for red/cyan

7.2.

103

SURFACES, CURVES AND POINTS

All plots can be drawn as anaglyph plots. To view this properly, you need red/cyan glasses.
The 3D e ect is amazing.
Plots can be turned and zoomed by the user, if the parameter user=1 is set (interactive plots).
The space key resets the plot to the start. Pressing a generates an anaglyph plot. To toggle
between turning the light source or the plot, press the l key.
There are many settings to change the look of the plot, the angle, the zoom factor, the viewing
distance or the colors. Have a look into the documentation of plot3d.
The center is the point the view looks at. It is usually the origin of the coordinate space, but
can be set to any other point. If the plot is interactive (user=1), the user can set the center with
the cursor keys, once he toggled into the center mode with the key c.
The plot commands plot2d and plot3d map to expressions and functions by default. This is so
to prevent strange errors, which occur, if functions are used in expressions, which are not safe for
vectors or matrices. However, expressions, which work for matrices due to the matrix language,
or functions, which are already de ned as mapping, would not need this. Then it is a bit faster
to swithc the mapping o with maps=0. This has no e ect, however, for plot2d and the default
adaptive evaluation.
Further Information
zoom(5)
viewdistance(2.5)
viewangle(45 )
viewheight(45 )
fillcolor(n,m)
reset()
f3daxis

7.2

Zoom factor.
Viewing distance.
Angle of view.
Angle above the x-y -plane.
Set the ll colors.
Resets to default parameters.
Another plot with axis.

Surfaces, Curves and Points

This section contains some examples for types of 3D plots. For a 3D surface, plot3d needs
three parameter functions in x and y, or three matrices. In any case, the surface is modeled by
a mapping f : Q ! R3 , where Q is a rectangle in the plane R2 .
>plot3d("cos(x)*cos(y)","sin(x)*cos(y)","sin(y)", ...
> xmin=0,xmax=2*pi,ymin=-pi/2,ymax=pi/2, ...
> hue=1,user=1,light=[1,0,1],frame=0);

This plots a ball. The parameter functions are simply expressions in x and y. Of course, functions
of the form f (x; y) can be used too.

104

CHAPTER 7.

FUNCTIONS OF SEVERAL VARIABLES

The following plot draws the Mobius strip. We compute three matrices for the three
parameters. The parameter hue=2 turns hue on, and the hue will not depend on the side of the
surface.
Example:

>x:=linspace(0,2*pi,100); y:=(-1:0.1:1);
>plot3d(cos(x)*(1+y/2*cos(x/2)),sin(x)*(1+y/2*cos(x/2)),y/2*sin(x/2),...
> frame=0,hue=2,max=0.8,scale=1.5);

Figure 7.3: Moebius strip

are drawn with three parameter functions and the optional parameter wire=1 (or
). Alternatively, three vectors can be used.

3D Curves
line=1

>plot3d("sin(x)","cos(x)","x/2Pi",wire=1,xmin=0,xmax=10pi,n=100,user=1);

Points in 3D

of the points.

are drawn with the parameter points=1. We need three vectors for the coordinates

The following commands generate a cloud of randomly normal distributed values in


space. The second plot shows a Brownian motion, which we get with a cumulative sum of the
points.

Example:

>A:=normal(3,10000); plot3d(A[1],A[2],A[3],points=1,style=".");
>B:=cumsum(A); plot3d(B[1],B[2],B[3],wire=1,anaglyph=1,user=1);

7.3.

SOLVING EQUATIONS OF SEVERAL VARIABLES

105

Figure 7.4: Brownian path as anaglyph

7.3

Solving Equations of Several Variables

To solve non-linear systems of equations of several variables, Euler has the fast Newton
algorithm and the Broyden method. The stable Nelder-Mead algorithm for minimization
can also be used. Moreover, there is a variant of the Newton algorithm delivering guaranteed
inclusions.

Figure 7.5: Solutions of two equations

Let us solve the system of equations


x2 + y 2 = 1; y = e xy :
For this, we write a function f as
[x; y] 7! [x2 + y2 1; y exp( xy)]:
Example:

106

CHAPTER 7.

FUNCTIONS OF SEVERAL VARIABLES

We seek the zeros of this function. The Broyden method works very well here. For the Newton
method, we need the Jacobian matrix of derivatives. We can compute it by hand in this simple
case.
>plot2d("x^2+y^2",r=1.5,niveau=1); plot2d("y-exp(-x*y)",niveau=0,add=1);
>function f(v) := [v[1]^2+v[2]^2-1,v[2]-exp(-v[1]*v[2])]
>broyden("f",[1,0])
0.7880470947328
0.6156149579756
>function Df(v) := [2*v[1],2*v[2];v[2]*exp(-v[1]*v[2]),1+v[1]*exp(-v[1]*v[2])]
>newton2("f","Df",[1,0])
0.7880470947328
0.615614957975

Alternatively, we can use Maxima to compute the derivatives. First, we store the two equations
in expressions, and de ne the function f with the help of these equations. The syntax is explained
in the chapter about programming.
>f1:="x^2+y^2-1"; f2:="y-exp(-x*y)";
>function f(v) ...
$ x:=v[1]; y:=v[2];
$ return [@f1,@f2];
$endfunction

Then we let Maxima compute the Jacobian at compile time of Df. The syntax is explained in
the chapter about Maxima.
>function Df(v) ...
$ x:=v[1]; y:=v[2];
$ return @:"jacobian([@f1,@f2],[x,y])")
$endfunction
>newton2("f","Df",[1,0])
0.7880470947328 0.6156149579756
>inewton2("f","Df",[1,0])
~0.78804709473275303,0.7880470947327548~
~0.61561495797557209,0.61561495797557297~

The functions now work exactly as above. However, we also tried the Interval Newton method
to get a close and guaranteed inclusion of the solution.
Another stable method is the Nelder-Mead algorithm, which minimizes functions f : Rn ! R.
We use it for the function f (v) = kvk.

7.4.

IMPLICIT FUNCTIONS

107

>function g(v) := norm(f(v))


>neldermin("g",[1,0])
0.7880470947328
0.615614957976

The algorithm is not very fast. For very high dimensions, it cannot be recommended.
There is also a generalization of the Newton method for functions from a lower into a higher
dimension, the Levenberg-Algorithm. It needs a derivative too, which we can compute with
Maxima. For a test, we compare with the Nelder algorithm.
>expr:="[x^3+y,x-y,x+y-1]"
[x^3+y,x-y,x+y-1]
>function f([x,y]) := @expr
>function Df([x,y]) := @:"jacobian(@expr,[x,y])"
>nlfit("f","Df",[2,1])
0.4063570133785 0.3109666275794
>function g([x,y]) := norm(f([x,y]))
>nelder("g",[2,1])
0.4063568110959 0.3109663066958

7.4

Implicit Functions

Euler can draw the solutions of f (x; y) = c for one or more values c (contour

plots). Use
with the parameter niveau=... for this. The values of c are either a number, or a row
vector of values. niveau="auto" or contour=1 will use equal spaced values. The additional
parameter hue=1 indicates the values of the functions with a shading. Black means low values,
and white means high values.
Alternatively, the function plot3d can be used. This yields a three dimensional plot with shading
and contour lines.
Example: Let us investigate the function f (x; y ) = xy y x for x; y > 0. First we plot the
solution of the equation xy = yx in the range 0  x; y  5.
plot2d

>function f(x,y) := x^y-y^x


>plot2d("f",a=0,b=5,a=0,b=5,niveau=0,hue=1);
>plot3d("f",xmin=2,xmax=3,ymin=2,ymax=3,user=1);

108

CHAPTER 7.

FUNCTIONS OF SEVERAL VARIABLES

Figure 7.6: Solutions of xy = yx

Then we investigate the intersection of the two curves of this solution. It is characterized by the
fact that the partial derivative of f to y on the line y = x becomes 0. It turns out, that the
intersection is in (e; e).
>:: diff(x^y-y^x,x), % | x:y, solve(%=0,y)
y - 1
x

x
y - y

log(y)

y
y
y - y log(y)

y
[y = %e, y = 0]

Chapter 8

Programming Euler
8.1

Functions

In the introduction, we have already met one-line functions. This kind of function de nition
is the most elementary and often good enough. One-line functions can use global variables
automatically. Alternatively, variables can be passed as arguments.
>function f1(x) := m*x+t
>t:=1; m:=-0.25; f1(3)
0.25
>function f2(x,m,t) := m*x+t
>f2(0:4,-0.25,1)
1
0.75

0.5

0.25

Euler can assign default values to parameters (default parameters). Those parameters need

no value, when the function is called.

>function logb(x,base=10) := log(x)/log(base)


>logb(100)
2
>logb(1024,2)
10

Multi-line functions begin with function and end with endfunction. They should contain
a return statement somewhere.

109

110

CHAPTER 8.

PROGRAMMING EULER

>function f3 (x)
$ if x<0 then return x^3
$ else return x^2
$ endif
$endfunction
>plot2d("f3",-1,1);

If a multi-line function does not return a value, it returns the value none, a string consisting of
the ascii character 1, which will never print.
It is possible to enter multi-line functions in the text window, either directly, or with the help of
the internal editor. To use the internal editor, press F9 in the function line. Have a look into
Section 3.7 for details.
When replaying the notebook, the user has to go through the function de nition line by line.
To avoid this, end the function line with three dots ... This will read the function with one
return. To make things easier, the ... string is automatically appended by the internal editor.
It might me more comfortable to edit all the functions needed in a notebook in an external le.
Edit the le with the external or internal editor, save it with the filename.e extension, and load
it into Euler with load filename. The le should be in the same directory as the notebook.
Otherwise, the load command must provide the complete path to the le.
You can use any simple text editor to edit Euler les. Euler comes with je, a Java editor.
There is also an internal editor. Both editors will use a temporary le in the user directory
if they are started in empty lines. They will use the le of the load command if the current
line starts with such a command. To start the internal editor for editing les, press F9 in a line
starting with load, to start the external editor use F10.
Example: Enter the following text into the internal editor (or paste it from the documentation),
and press Interpret. Simply press F9 or F10 in an empty line to start the editor with a temporary
le. The text between comment and endcomment will be printed as a comment while loading.
comment
Definition of f3(x).
endcomment
function map f3 (x)
if x<0 then return x^3
else return x^2
endif
endfunction

8.1.

111

FUNCTIONS

This is how the notebook looks.


>load "C:\Dokumente und Einstellungen\Rene\EulerTemp.e"
Definition of f3(x).
>f3(-2:2)
-8 -1 0 1 4

The map keyword in the de nition of f3 makes the function work for vector input. We will
discuss this trick later in the section about functions and the Euler matrix language.
Within an Euler function, comments can be entered at any place with //, or at the beginning
of the line with ##. The ## comment lines directly at the start of the function de nition are
used as help lines. These lines are printed with help functionname.
Example: We enter the following code with the internal editor. To do this, type function into
an empty line, and press F9. In the internal editor, paste or type the following lines. End the
editor with the OK button, and press return to de ne the function.
function map sinctest (x) ...
## Computes sin(x)/x taking care of x=0
if x~=0 then return 1
else return sin(x)/x
endif
endfunction

sinctest

tion.

then works just like any other function, and help

sinctest

prints help for this func-

>plot2d("sinctest",0,2pi);
>help sinctest
sinctest is an Euler function.
function map sinctest (x)
Entered from command line.
Computes sin(x)/x taking care of x=0

All pre-de ned Euler functions contain help lines. The rst help line should contain a function
summary, since this line is shown in the status line as immediate help, after the user has entered
the opening bracket for the function parameters. Moreover,

112

CHAPTER 8.

PROGRAMMING EULER

>help util.e

will print all function de nitions in the Euler le util.e, including the rst line of the help.
An Euler le with functions can also contain items for the user menu. These items are commands the user can paste at the current cursor positions. The commands can contain placeholders
like ?expression. If the user starts typing in front of a placeholder the placeholder is removed.
The cursor right key positions the cursor to the next placeholder. The syntax for the menu is
as follows.
submenu My Functions
addmenu myfunction("?expression",?xstart)
addmenu ?variable=solve("?expression",?xstart)

The submenu can be omitted. In this case a submenu with the le name will be used. Weather
the command is a full command as in the second example or only a function is a matter of taste.
Euler uses untyped variables and parameters by default. To avoid strange error messages and
bugs, it is possible to require a type for a parameter of a function. Enter the type after the
variable separated by :.
In the following example, we do not want to use the function for complex numbers or intervals,
since it will no longer work properly.
>function map signum (x:real) ...
$ if x<0 then return -1;
$ elseif x==0 then return 0;
$ else return 1;
$ endif;
$endfunction
>signum(I)
Function signum needs a real for x
error in :
signum(I)
^

There are the following types for parameters.

8.2.

FUNCTIONS AND THE MATRIX LANGUAGE

113

Further Information
real
complex
interval
numerical
integer
positive
nonnegative
scalar
vector
column
natural
index
indices
number
string
cpx

real numbers
complex or real numbers
intervals or real numbers
any number
integer numbers
positive numbers
non-negative numbers
numbers, but not matrices or vectors
row vectors of numbers
column vectors of numbers
short for nonnegative integer scalar
short for positive integer scalar
short for positive integer vector
short for real scalar
strings
compressed sparse matrices

Some of these types can be combined. E.g., real scalar means a real number, not a complex
number or an interval, which is also not a vector or a matrix. string vector allows only vectors
of strings.
Overwriting built-in or pre-de ned functions is not allowed by default. With the keyword
overwrite, this is possible nevertheless. To access a built-in function with the same name,
prepend an underscore.
Rede ning built-in functions must be done with care. The following rede ntion of sin, which
works for degrees, is not recommended. It might be wiser to use a separate name line sindeg
for this purpose.
>function overwrite sin(x) := _sin(rad(x))
>sin(45)
0.7071067811865

Further Information
comments off
arg1,arg2,...
argn

8.2

Switches o comments while loading.


Alternative way to access parameters.
Number of parameters given.

Functions and the Matrix Language

Many functions work for matrices automatically. This is so, since expressions in Euler work
for matrix and vector input. However, if the function contains control structures, it will usually
not work for vector input.

114

CHAPTER 8.

PROGRAMMING EULER

Euler can map

a function to matrix arguments. The easiest way is to append map to the


function name. Alternatively, there is a function map("f",...), which maps the function f to
the other arguments.
But a function can also be de ned as a mapping function. In this case, the function must have
scalar parameters, and must return a scalar, not a vector. Euler will automatically map the
function to the elements of the matrix.

>function map f(x:number) ...


$ if x<0 then return x^2
$ else return x^3
$ endif
$endfunction
>f(-1:0.5:1)
1 0.25 0 0.125 1

The function would not work for vector input without mapping. The reason is, that x < 0 only
evaluates to true, if all elements of x are negative. In other words, the if does not branch down
to the elements of the x. By default, if conditions for vectors are deprecated, and need to be
replaced by all.
Example: Conditions on vectors make sense for a xpoint iteration, as in the following example.
>A=[0.2,0.5;0.4,0.6]; b=[1;1];
>function fixpointiter (x) ...
$ global A,b;
$ repeat
$ xnew=A.x-b;
$ if all(xnew~=x) then return xnew endif
$ x=xnew;
$ end;
$endfunction
>fracprint(fixpointiter([0;0]))
-15/2
-10

Arguments can be protected from mapping with the semicolon. This works either at runtime or
at complile time of the function.
Example: We want to evaluate di erent polynomials depending on x > 0 or x  0. The
evaluation points and the polynomials are parameters of f. Since the function does not work for
vector values, we de ne it using map. But we do not want to map f to the polynomial coecients,
of course.

8.3.

MULTIPLE RETURN VALUES

115

>function map f(x:scalar; p:vector, q:vector) ...


$ if x>0 then return polyval(p,x)
$ else return polyval(q,x)
$ endif
$endfunction
>plot2d("f(x,[0,1,2],[0,1])",-1,1);

The quick computation of Chebyshev polynomials uses di erent algorithms for x < 1,
1; 1] and x > 1. Note, that the following function is already contained in Euler.

Example:

x2[

>function cheb (x,n) ...


$ if x>1 then
$
w:=(x+sqrt(x^2-1))^n
$
return (w+1/w)/ 2;
$ elseif x<-1 then
$
signum:=-mod(n,2)*2+1
$
w:=(-x+sqrt(x^2-1))^n
$
return signum*(w+1/w)/ 2;
$
else
$
return cos(n*acos(x));
$
endif;
$endfunction

We can even compute many Chebyshev polynomials of di erent degree at once.


>x:=-1:0.01:1; n:=(1:4); plot2d(x,cheb(x,n));

8.3

Multiple Return Values

Often we need to pass several return values from a function. We do not want to use global
variables for this. Instead, Euler can return more than value with the return statement. The
syntax for this uses curly brackets around comma separated values.
Of course, these return values can be assigned to multiple variables. The list of variables is
enclosed by curly brackets too.

116

CHAPTER 8.

PROGRAMMING EULER

Figure 8.1: Chebyshev polynomials T1 till T4

Example:

We sort two values, and return both in the correct order.

>function sort2 (a,b)


$ if a<b then return {a,b}
$ else return {b,a}
$ endif
$endfunction
>{x,y}:=sort2(2,3); x, y,
2
3
>{x,y}:=sort2(3,2); x, y,
2
3

To sort a vector Euler has the sort function. The function returns the sorted
vector, and the new indices of the elements, such that in the following example i[ind] is the
sorted vector j. This is useful to permute any other vector in the same way.

Example:

>i:=shuffle(6:10)
7 10 8 6 9
>{j,ind}=sort(i); j
6 7 8 9 10
>ind

8.4.

117

GLOBAL VARIABLES

4 1 3
>i[ind]
6 7 8

10

It is a bit tricky to get the inverse permutation. However this can be done by sorting the indices.
>{k,invind}=sort(ind);
>j[invind]
7 10 8 6 9

Further Information
Finds a number in a sorted vector.
Sort the rows of a matrix in lexicographical order.

find
lexsort

8.4

Global Variables

Inside a function, only the local variables and the parameters are visible. Local variables are
the variables declared in the function, or the parameters that had values. An exception are
global variables ending with $, which are visible from every function. Those variables should
be used for units.
To access global variables, use the useglobal command in the function, or the command global
varname. You still cannot change these global variables in type or matrix size, but you can change
their value.
Note that one-line functions always contain the useglobal statement. So they can see global
variables.
Example: In the following example we set the diagonal of a global matrix to some given value.
>function setA (s)
$ global A;
$ A=setdiag(A,0,s);
$ return A;
$endfunction
>A:=[1,2;3,4]
1
3
>setA(4);

2
4

118

CHAPTER 8.

PROGRAMMING EULER

>A
4
3

2
4

Euler passes variables by reference. However, it is not possible to change the value of a
variable, which is used as a parameter. To circumvent this, start the name of the parameter with
a %. In this case, changing the parameter will actually change the value of any variable passed
to it. The type or the matrix size of such a variable cannot be changed, however.
>function setA (%A,s)
$ %A=setdiag(%A,0,s);
$endfunction
>A:=[1,2;3,4]
1
3
>setA(A,4);
>A
4
3

2
4

2
4

Additional variables can be passed to a function with an assigned parameter. Those variables
work like local variables in that function.
Example: The function evaluate evaluates a string as an Euler expression. In the example,
we use it inside the one-line function test. So it can see the local variables of test, and global
variables. To set the values for x and y, we set these as local variables in test.
>function test (expr) := evaluate(expr)
>test("x*y",x=2,y=3)
6

The utility functions plot2d and plot3d, as well as many other functions in Euler, use a
mixture of parameters with default values and assigned parameters. This works well, since
assigned parameters override the default values of parameters with the same name.
>function test(x,a=2) := a*x
>test(4)

8.5.

CONTROL STRUCTURES

119

8
>test(4,a=3)
12

We remark that expr() works like evaluate(expr) with the important di erence, that it can
only see global variables, or variables passed to it as in expr(x=2,y=3), not local variables if the
function containing the evaluation.
8.5

Control Structures

Control structures change the ow of execution in a function. There are two types: conditional
branches and loops.
Conditional branches are possible with the if statement. if always has to end with endif.
After the condition, there is an optional, but recommended then. An alternative branch is
possible with else. elseif works like an if statement in the else branch. However, only one
endif is needed.
Example: We can implement the signum function in Euler as follows. Note, that Euler has
this function already as sign. When comparing with 0, it is wise to use ~=. This comparison
uses the internal epsilon.
>function signum (x)
$ if x>0 then return 1
$ elseif x~=0 then return 0
$ else return -1
$ endif
$endfunction

If conditions are connected with and or or, they are evaluated only as much as necessary. This
is called a condition shortcut.
>function test (a,b) ...
$ if a^3+1>=0 and b<sqrt(a^3+1) then return 1
$ else return 0
$ endif;
$endfunction

120

CHAPTER 8.

PROGRAMMING EULER

Note, that a3 + 1 is not computed, if a3 + 1 < 0.


These logical operators must only be used in if conditions. To compute a condition for variables,
use the ordinary logical operators &&, || of Euler.
>function isbetween(x,a,b) := (x>=a)&&(x<=b)

There are also several loops in Euler. The basic repeat loop is an eternal loop. To break it,
use the break statement, preferably inside an if structure. The loop loop is an integer loop
running between two integer values. The for loop counts a variable with an optional step value
from the starting value to the end value.
The following loops all count from 1 to 10.
>function s1
$ n:=1
$ s:=0
$ repeat
$
s:=s+n
$
n:=n+1
$
if n>10 then break; endif;
$ end;
$ return s;
$endfunction
>function s2
$ s:=0
$ loop 1 to 10;
$
s:=s+#
$ end;
$ return s;
$endfunction
>function s3
$ s:=0
$ for i=1 to 10 step 1
$
s:=s+i
$ end;
$ return s
$endfunction

Of course loops can be put one into the other. This is called a double loop. If the inner loop
is broken with a break statement, the outer loop will continue to run.

8.5.

CONTROL STRUCTURES

121

For a more complicated example, we write a function, which prints the numbers till
3000 as Roman numbers.
Example:

>function roman (x) ...


$ x=floor(x);
$ if x<1 then error("x<0");
$ elseif x>3000 then error("x>3000");
$ endif
$ s:="";
$ repeat
$
if x>=1000 then s:=s|"M"; x:=x-1000;
$
elseif x>=900 then s:=s|"CM"; x:=x-900;
$
elseif x>=500 then s:=s|"D"; x:=x-500;
$
elseif x>=400 then s:=s|"CD"; x:=x-400;
$
elseif x>=100 then s:=s|"C"; x:=x-100;
$
elseif x>=90 then s:=s|"XC"; x:=x-90;
$
elseif x>=50 then s:=s|"L"; x:=x-50;
$
elseif x>=40 then s:=s|"XL"; x:=x-40;
$
elseif x>=10 then s:=s|"X"; x:=x-10;
$
elseif x>=9 then s:=s|"IX"; x:=x-9;
$
elseif x>=5 then s:=s|"V"; x:=x-5;
$
elseif x>=4 then s:=s|"IV"; x:=x-4;
$
elseif x>=1 then s:=s|"I"; x:=x-1;
$
else break;
$
endif;
$ end;
$ return s;
$endfunction
>roman(1968)
MCMLXVIII

Control structures can also be used outside of functions. However, they have to t into a single
command line.
>summe=0; for i=1 to 10; summe=summe+i; end; summe,
55

Functions can call themselves recursively (recursive functions). This yields very elegant programs. The stack for recursive calls is limited, however.
Example: We breakup a string in substrings separated by a blank. The function strfind nds
a string in another string. If the string contains a blank, we print the rst part, and proceed to
scan the second with a recursive call.

122

CHAPTER 8.

PROGRAMMING EULER

>function breakup (str) ...


$ n=strfind(str," ",0);
$ if n>0 then substring(str,1,n-1), breakup(substring(str,n+1,-1));
$ else str,
$ endif;
$endfunction
> breakup("This is a test");
This
is
a
test

Further Information
and, or
&&, ||
error(String)
index

8.6

Connects conditions in if (with shortcut).


Boolean \and" and \or", also for vectors.
Error message and function abort.
Alternative for the loop index #.

Vector Parameters

Often a function requires a vector of speci c length. We might want to assign the vector elements
to variables. This is possible with the following syntax.
>function f([x,y]) := [x*y-1,x-y]
>f([1,1])
0
>f(1,1)
0

0
0

As you see, the function can be used with scalars too.


8.7

Functions as Parameters

Many functions in Euler expect an expression or a function name. Examples are plot2d or
. In this section, we explain how to write those functions.
To evaluate a function given by name, simply use a variable fvar containing the name, and
call the contained function as in fvar(...). To check if a string variable contains a function,
we can use isfunction
plot3d

8.7.

FUNCTIONS AS PARAMETERS

123

To evaluate an expression contained in a string, we can use evaluate. As discussed above,


evaluate inside a function sees the local variables of the function, and the global variables only
if useglobal is set.
>function test(x,f)
$ if isfunction(f) then return f(x)
$ else return evaluate(f)
$ endif
$endfunction
>test(2,"sin")
0.9092974268257
>test(2,"x^2")
4

There is an easier way to do this. The command exprvar() evaluates the string contained in the
variable exprvar. This version allows additional arguments, which are assigned to the variables
x, y and z. More arguments can be given with assigned parameters, as in exprvar(2,a=4).
During the evaluation, only the parameters and global variables are visible.
>function test(x,f) := f(x)
>test(2,"sin") // evaluate a function at 2
0.9092974268257
>test(2,"x^2") // evaluate an expression at x=2
4

There is one more problem. Suppose f is called inside g(f), where f is given as a string parameter
to g. Then we need a way to pass additional parameters to f via g. This is done using the args()
function and the semicolon ; (semicolon parameters). args() simply denotes all arguments
after the semicolon. There is a rule that semicolon parameters must be given before any assigned
parameters.
In the following example, we pass the parameter 5 of test to f. The actual call to f is f(2,5).
>function test (x,f)
$ return f(x,args())
$endfunction
>function f(x,a) := a*x
>test(2,"f";5)
10

124

CHAPTER 8.

PROGRAMMING EULER

The same can be done with expressions. The following commands work well, since a is a global
variable.
>a:=2; plot2d("x^2-a",1,2);

However, the same commands will not work insinde a function, since a is not de ned globally.
We need to pass the local variable a as a semicolon parameter to the plot function. Of course,
values cannot be passed to expressions in the same way, since expressions look for variables by
name.
>function test(a) ...
$ plot2d("x^2-a",1,2;a);
$endfunction
>test(4)

We compute the Fourier coefficients of functions numerically. Those coecients


are de ned by
Z
1
ak =
f (x) cos(kx) dx


Example:

For the integral, we use the Romberg method.


We de ne a function, evaluating f (x) cos(kx). The function name f and the degree k will be
given to the romberg method as additional parameters. The function romberg will pass these
parameters to the function it integrates. Using map, we compute the coecients from k = 1 to
k = 5.
>function fcos (x,f,k) := f(x)*cos(k*x)
>function map a(f,k) := romberg("fcos",-pi,pi;f,k)/pi
>function f(x) := x^2
>fracprint(a("f",1:5));
-4 1 -4/9 1/4 -4/25

The result can be checked with Maxima.

8.8.

125

FUNCTIONS AND MAXIMA

>:: integrate(x^2*cos(3*x),x,-%pi,%pi)/%pi
4
- 9

8.8

Functions and Maxima

Often, we want to use Maxima to compute derivatives or other expressions. This can be done
using the mxm command, as explained in the chapter about Maxima. But it might be much
better, to do this during the de nition of a function. To call Maxima at compile time, use
@:"...". The expression in the string will be evaluated by Maxima and the result will be
inserted into the function body (evaluation at compile time).
Example: We write a function for the tangent g (x) to the function xx in a point s. The
derivative of the function is computed while the function is de ned. To see this, have a look at
the internal print of g.
>function g(x,s) := s^s+ @:"diff(s^s,s)" *(x-s)
>type g
function g (x,s)
useglobal; return s^s+ s^s*(log(s)+1) *(x-s)
endfunction
>plot2d("x^x",0,2); plot2d("g(x,1)",add=1);

This is useful, if we want to de ne functions for derivatives. The Newton method requires a
function, which returns the Jacobian of a function. We can de ne such a function from an
expression using the following syntax.
>fx="x*y-1"; fy="x-y";
>function f([x,y]) := [@fx,@fy]
>function Df([x,y]) := @:"jacobian([@fx,@fy],[x,y])"
>newton2("f","Df",[2,1])
1
1

The function Df is correctly de ned.

126

CHAPTER 8.

PROGRAMMING EULER

>type Df
function Df ([x, y])
useglobal; return matrix([y,x],[1,-1])
endfunction

To create such a function for varying expressions, we cannot evaluate at compile time. The
expression is passed Maxima command with the @str syntax. Then @str is replaced by the
content of the string variable str before Maxima is called.
>function g(t,x,f)
$ return evaluate("::@f")+ ..
$
evaluate("::diff(@f,x)")*(t-x)
$endfunction
>g(2,1,"x^x")
2
>plot2d(g(x,1,"x^x")); plot2d("x^x",add=1);

We need to call Maxima with a given expression at each call of the tangent function. Note, that
this is not very e ective.
8.9

Error messages in Euler

Euler is a very exible system, using an interpreter and untyped variables. The downside of

this is that the user is sometimes faced with strange error messages. In this section, we like to
explain some of theses problems.
The rst versions of Euler used the Matlab style v(i) to access an element of a vector, as
an alternative to v[i]. This opens the door to all sorts of errors. In fact, the results of v(i)
depends on the type of v. For functions, strings and vectors there is a di erent meaning. In
fact, an expression like (3+4)(4+5) worked, resulting in an empty vector.
Starting with the recent versions, Euler has ags to prevent these problems. By default, these
ags are set. For some time, the restrictions were relaxed in functions. But now, the user must
expicitely de ne the function as a relaxed function, if he wants to use the old style. To do this,
use the command relax at the start of the Euler le containing the de nition of the function.
This, of course, is not recommended.
Here some examples of error messages you might get in the most recent versions.

8.9.

ERROR MESSAGES IN EULER

>v=1:3; v(2)
Unexpected "(". Index () not
In Euler files, use relax to
error in :
v=1:3; v(2)
^
>sin[0.4]
sin is not a variable!
error in :
sin[0.4]
^
>(1+4)(5+6)
Unexpected "(". Index () not
In Euler files, use relax to
error in :
(1+4)(5+6)
^
>(1+4)[5+6]
Index 11 out of bounds!
error in :
(1+4)[5+6]
^

127

allowed in strict mode!


avoid this.

allowed in strict mode!


avoid this.

The last examples used to yield a zero sized vector. Those vectors are practical for some purposes,
but may lead to big confusion. The following is an example of a valid use.
>v:=[]; x:=1; loop 1 to 10; v:=v|x; x:=cos(x); end;
>v
Column 1 to 3:
1
0.5403023058681
0.8575532158464
Column 4 to 6:
0.6542897904978
0.7934803587426
0.7013687736228
Column 7 to 9:
0.7639596829007
0.7221024250267
0.7504177617638
Column 10 to 10:
0.7314040424225

However, the following two versions are much better, especially the second, which is also more
ecient, since the vector v does not have to be expanded.

128

CHAPTER 8.

PROGRAMMING EULER

>x:=1; v:=[x]; loop 1 to 9; x:=cos(x); v:=v|x; end;


>x:=1; v:=zeros(1,10); v[1]=x; loop 2 to 10; x:=cos(x); v[#]=x; end;

Of course, this can also be achieved with iterate.


>iterate("cos(x)",1,10)

As mentioned in the section about parameters, untyped parameters may lead to very cryptic
error messages, if a parameter of unexpected type is used.
>function myplot(f,a,b) := plot2d(f,a,b,color=10,thickness=3,title="test")
>myplot("x^2",-1,1);
>myplot("x^2",-1,1:4);
Error : Illegal x or y in plot
Error in :
error("Illegal x or y in plot");
^
Error in function plot
Error in function plot2d
Error in function myplot
Error in function myplot

It is not really clear, what happened. Thus it is much better to avoid this confusion. with typed
paramters.
>function myplot(f:string,a:number,b:number) := plot2d(f,a,b)
>myplot("x^2",-1,1);
>myplot("x^2",-1,1:4);
Function myplot needs a scalar for b
error in :
myplot("x^2",-1,1:4);
^

Chapter 9

Statistics
9.1

Random Numbers

Euler can generate vectors and matrices lled with random numbers. The function random

generates a matrix of numbers equi-distributed in [0; 1], and normal generates 0-1 normal distributed numbers. seed can be used for setting a xed start value.
Example: We generate 1000 normal distributed values with mean value 1000 and standard
deviation 5, and plot a histogram of the values.
>a:=normal(1,1000)*5+1000;
>plot2d(a,distribution=20,style="/");

The function histo prepares the data for the histogram plot, computing the frequencies in a
given number of intervals. So we can do the same in two steps.
>{x,y}:=histo(a,20);
>plot2d(x,y,bar=1,style="/");

Example:

values.

For another example, we throw a dice 600 times, and count the frequencies of the

>a:=floor(random(1,600)*6);
>count(a,6)
91
100
112

100

95

129

102

130

CHAPTER 9.

STATISTICS

Figure 9.1: Normal distributed values

Euler Can also shuffle vectors with shuffle. As an example we generate lottery
numbers 6 out of 49.
Example:

>z:=shuffle(1:49); sort(z[1:6])
7
11
14

9.2

29

34

39

Distributions

Euler can compute many distributions and their inverses. The most important case is the

.
Example: At 1000 throws of a coin the expected numbers of heads is distributed with mean
value 500 and
p
 = 1000  0:5  0:5:
We compute the probability to get more than 520 times head, and when the probability gets less
than 0.1%. Moreover, we compute a 99% con dence interval.

normal distribution

>m:=500; s:=sqrt(1000*0.5*0.5); 1-normaldis((520-m)/s)


0.102951607314
>ceil(invnormaldis(1-0.1%)*s+m)
549
>k:=invnormaldis(99.5%)-0.5; d:=m+ceil(k*s)
533

9.3.

131

DATA INPUT AND OUTPUT

>~m-d,m+d~
~467,533~

Note that the function normaldis in Euler scales in another way than the function erf, which
is also available. All distributions in Euler are implemented as distribution functions, which
grow from 0 to 1.
The approximation to the binomial distribution in the example above can also be computed
exactly. The functions binsum and for large n normalsum do that.
>1-binsum(520,1000,0.5)
0.09738316423031
>invbinsum(99.9%,1000,0.5)
550

Further Information
chidis
tdis
invtdis
fdis

9.3

chi distribution.
Student T-distribution.
Inverse T-distribution.
F-distribution.

Data Input and Output

It is often necessary to read and write data to external les. Euler supports this with a lot of
functions on di erent levels. Euler can open only one le for read and one for write at each
time. To open a file use the open command, and to close it, use the close command. Some
functions open and close les automatically.
Without a path, les are opened in the current directory. Opening or saving a notebook
sets the current directory to the notebook directory. Another good place for notebooks is the
user folder Euler Files in the home directory of the user. To get the path to this folder use
userhome.
>filename=userhome()|"test.dat";

132

CHAPTER 9.

STATISTICS

We generate 10000 random numbers, and write these numbers into a le test.dat.
Then we read these numbers back from the le. The high level functions writematrix and
readmatrix open and close the le automatically. The matrix is written line by line. To avoid
overlong lines, it is better to use a column vector for the random matrix. The le will contain
the numbers one in each line.
Example:

>n:=10000; a:=random(n,1);
>writematrix(a,"test.dat");
>b:=readmatrix("test.dat");
>size(b)
10000
1

To append another matrix to the same le, we open the le in the appending mode "a".
The write mode "w" would delete the content of the le. Then we write the matrix with
writematrix, and close the le. To read both matrices, we open the le with the read mode
"r", and use readmatrix twice without the le name parameter.
>open("test.dat","a");
>writematrix(random(2,2));
>close();
>open("test.dat","r");
>b:=readmatrix();
>readmatrix()
0.143192
0.8242
0.0307746
0.654422
>close();

There are numerous elementary functions to read and write data. One useful function is
getvector, or getvectorline. This function reads an unknown, but limited number of numbers
(but with a decimal point, not a comma). Intermediate text is skipped. getvectorline stops at
the end of each line. The functions return the data and the count. Additionally, getvectorline
returns the line in string from. The functions are more e ective and faster than readmatrix.
In the following example, we use the write command to output a string, and putchar(10) for
a line feed.
>open("test.dat","w");
>write("Two Numbers: 1000 2000"); putchar(10);
>close();

9.4.

133

STATISTICAL TESTS

>open("test.dat","r");
>{v,n,s}:=getvectorline(1000);
>close();
>s
Two Numbers: 1000 2000
>n
2
>v
1000
2000

Further Information
getline
eof
dir
dir("*.e")
remove
cd(...)

9.4

Reads a line as a string.


Test if the le has been read completely.
Lists the current directory.
Lists all Euler les.
Deletes a le.
Changes the working directory.

Statistical Tests

Euler knows the basic statistical functions mean and dev. The latter computes the standard
deviation of the sample. Moreover, Euler can compute some statistical tests.

We test a series of 0-1 normal distributed random numbers for the mean value 0.5
with a
. Of course, we will most likely be able to reject the hypothesis that the
sample is from distribution with mean value 0.5 or higher.
Example:
student-T test

>a:=normal(1,20);
>ttest(mean(a),dev(a),20,0.5)
0.00101056390067

Further Information
tcomparedata
chitest
tabletest
varanalysis
mediantest
ranktest
wilcoxon

Tests two sample on equal distribution.


Test on equal distribution using the 2 test.
Test on independence of table rows.
Test on the same mean value.
Test on same mean value.
Test on same mean value.
Compares mean values.

134

CHAPTER 9.

STATISTICS

Chapter 10

Exact Arithmetic
10.1

Exact Scalar Product

Solving a linear system Ax = b sometimes yields large errors, even if the system is given exactly.
This is the case, if the matrix A is badly conditioned. I.e., it has very large and very small
eigenvalues. We have
kxk  kAk  kA 1 k kbk
kxk

kbk

with any compatible matrix norm.


Example: Since 123452 2  13  5861501 = 1, the following matrix has large elements, but a
very small determinant. The matrix is almost singular, and not well conditioned. Consequently,
we get large rounding errors in the Gau algorithm.
>A:=[12345,26;5861501,12345]
12345
5861501
>b:=A.[1;1]; A\b
1.000000021578
0.9999897544764

26
12345

If we compute the rst step of the Gau algorithm in Euler and Maxima we clearly see the
problem. The accuracy of the result is only 7 digits.
>B:=A; B[2]:=B[2]-(B[2,1]/B[1,1])*B[1]
12345

26

135

136

CHAPTER 10.

EXACT ARITHMETIC

0
-8.10044548416e-005
>mxmeval("12345-5861501/12345*26")
-8.100445524504e-005

To improve this result, we use a residual iteration. For this, we compute the error r = Ax b,
and correct the wrong solution x by the solution d of Ad = r. For this technique to work, we
must compute the residuum exactly. To do this, Euler has an exact scalar product using a
long accumulator.
>x:=A\b
1.000000021578
0.9999897544764
>r:=residuum(A,x,b)
-2.989164471501e-012
-5.893452392769e-010
>x:=x-A\r
1
1

The procedure is implemented in the function xlgs.


>xlgs(A,b)
1
1

We remark that it does not help to compute the residuum the simple way. It will be too bad to
help.
>x:=A\b
1.000000021578
0.9999897544764
>r:=A.x-b
-3.637978807092e-012
-9.313225746155e-010
>x-A\r
1.000000000882
0.9999995813157

10.2.

GURARANTEED INCLUSIONS

137

We want to stress here, that the method is only useful for systems, which are given in an exact
way. If the systems contain errors in the parameters, the seemingly exact results of xlgs have
to be checked carefully using interval methods (see the next section).

Figure 10.1: Errors of a simple evaluation of a polynomial

The following example is due to Rump et al. The residual iteration can be used to
evaluate badly conditioned polynomials. Euler implements this in the xpolyval command.
Example:

>p:=[-945804881,1753426039,-1083557822,223200658];
>t:=linspace(1.61801916,1.61801917,100);
>plot2d(t-1.61801916,polyval(p,t));
>plot2d(t-1.61801916,xpolyval(p,t,eps=1e-17));

Further Information
help accu

10.2

Lists the functions of the long accumulator.

Guraranteed Inclusions

The residual iteration is useful to nd exact solutions of exact equations. If the parameters of
the equations are inexact, we can only hope to produce as close inclusions of the solution as
possible.
Euler uses the function ilgs to get a guaranteed and narrow inclusion of the solution of a
linear system. The idea has been described by Rump et al. This is an iteration using interval
arithmetic. The guaranteed inclusion follows from a x point theorem.

138

CHAPTER 10.

EXACT ARITHMETIC

We solve the equation of the last section with ilgs. The experiments below show
that we get a narrow inclusion only if we assume that the equation is exact. Extending the
parameter intervals leads to bad inclusions or even failure. In this case the parameter intervals
include cases, where the system does not have a solution.

Example:

>ilgs(A,b)
~0.99999999999999978,1.0000000000000002~
~0.99999999999999978,1.0000000000000002~
>ilgs(~A~,~b~)
~0.99999986,1.0000002~
~0.99993,1.0001~
>ilgs(A0.5,b0.5)
Error : Pseudo inverse not good enough.
Error in :
if (rho>=1); error("Pseudo inverse not good enough."); endif;
^
Error in function ilgs
>B:=A0.5; B[1,1]*B[2,2]-B[1,2]*B[2,1]
~-2.9e+006,2.9e+006~

The inclusion method can also be used for non-linear systems, if we can compute the derivative
of the function. Euler implements the interval Newton method. The derivative can be
computed by Maxima.
Compute the solution of e x = x. The result is a very narrow interval. mxminewton
calls Maxima to compute the derivative automatically.

Example:

>inewton("exp(-x)-x","-exp(-x)-1",1,2)
~0.56714329040978362,0.56714329040978406~
>mxminewton("exp(-x)-x",1,2)
~0.56714329040978362,0.56714329040978406~

The interval Newton method is available in several dimensions too. In the following
example, we solve
xy = 1; x2 + y 2 = 4:
It is necessary to compute the Jacobian matrix. We use Maxima for this task in Df at compile
time. See the section about programming Euler for an explanation of this technique.
Example:

10.2.

GURARANTEED INCLUSIONS

>f1:="x*y-1"; f2:="x^2+y^2-4";
>function f(v)
$ x:=v[1]; y:=v[2];
$ return [@:"@f1",@:"@f2"]
$endfunction
>function Df(v)
$ x:=v[1]; y:=v[2];
$ return @:"jacobian([@f1,@f2],[x,y])";
$endfunction
>inewton2("f","Df",[1,2])
Column 1 to 1:
~0.51763809020504115,0.51763809020504203~
Column 2 to 2:
~1.931851652578135,1.931851652578138~

Further Information
mxmibisectfxy

f (x; y ).

Finds possible intervals containing zeros

139

140

CHAPTER 10.

EXACT ARITHMETIC

Chapter 11

Algorithms in Euler
11.1

Differential Equations

Solving differential equations numerically is one of the important applications of a software


like Euler. In this section, we discuss the Runge method, and a method to obtain guaranteed
inclusions.
Example: We solve the intial value problem
y
; y (1) = 1:
y0 =
x
using the Runge method. The solution is y = 1=x. runge accepts an expression in x and y, or a
function. We can either get all intermediate values, or only the values of the solution at selected
points. In the latter case, we need to specify the number of points to be computed between our
selected points.
>x:=1:0.01:10 y:=runge("-y/x",x,1); // get all 1000 values
>plot2d(x,y);
>y[-1]
0.1
>runge("-y/x",[1,10],1,100) // get only one value, and use 100 points
1
0.1

We solve the initial value problem


y 00 = a sin(y ); y (0) = 0; y 0 (0) = b
using the adaptive Runge method. This second order di erential equation must be rewritten
into a rst order equation in the plane.
   0

d y (x)
y (x)
= a sin(y(x))
dx y 0 (x)
141

Example:

142

CHAPTER 11.

ALGORITHMS IN EULER

Then runge and adpativerunge expect a function f(x,y), computing y0 . Both y and y0 have
to be row vectors.
>function f(x,y) := [y[2],-a*sin(y[1])]
>a:=1; b:=1;
>x:=0:0.1:10; y:=adaptiverunge("f",x,[0,b]);
>plot2d(x,y[1]);

We then want to determine the rst zero of the solution to get the frequency of the pendulum.
To do this, we set up a function to solve for y(x), and solve y(x) = 0 with the secant method.
>function h(x)
$ global b;
$ v=adaptiverunge("f",[0,x],[0,b]);
$ return v[1,2];
$endfunction
>secant("h",3,4)
3.371500709626

Of course, the solution of the approximating di erential equation y00 = ay for the pendulum
has its rst zero at . Taking a smaller amplitude b makes the error much smaller.
>b=0.01;
>secant("h",3,4)
3.14161228882

To solve a boundary value problem


y 00 = a sin(y ); y (0) = 0; y ( ) = 1
in Euler, we use the shooting method. We set y0(0) = x, and solve y() = 1 for x.
Example:

>a=1;
>function g(x)
$ v=adaptiverunge("f",[0,pi],[0,x]);
$ return v[1,2]-1;
$endfunction
>secant("g",1)
1.521612414054

11.1.

DIFFERENTIAL EQUATIONS

143

Figure 11.1: Pendulum y00 = sin(y)

Euler can plot the direction eld of a di erential equations with the functions vectorfield
and vectorfield2.
>vectorfield2("y","-sin(x)",-2,2,-2,2);
>function f(x,y) := [y[2],-sin(y[1])]
>x:=0:0.01:10; y:=runge("f",x,[0,1]);
>plot2d(y[1],y[2],add=1);

With Maxima, we can solve many di erential equations exactly. Use ode2 for the general
solution. With ic1 and ic2, you can get the constants for initial value problems or boundary
value problems.
Example: We solve the initial value problem
y 00 + y 0 + y = sin(x); y (0) = 0; y 0 (0) = 1
with Maxima, and plot the result in Euler.
>:: eq := diff(y,x,2)+\diff(y,x)+y=sin(x)
2
d y
dy
--- + -- + y = sin(x)
2
dx
dx

144

CHAPTER 11.

ALGORITHMS IN EULER

Note the apostrophe in the de nition of the equation. It prevents the execution of the diff
function.
>:: gsol := ode2(eq,y,x)
- x/2
sqrt(3) x
sqrt(3) x
y = %e
(%k1 sin(---------) + %k2 cos(---------)) - cos(x)
2
2
>:: sol := rhs(ic2(gsol,x=0,y=0,diff(y,x)=1))
- x/2
sqrt(3) x
sqrt(3) x
%e
(sqrt(3) sin(---------) + cos(---------)) - cos(x)
2
2
>plot2d("::sol",0,2*pi);

To get a guaranteed inclusion for an initial value problem, we can use the function mxmidgl.
This function computes very high derivatives of the di erential expression with Maxima. The
degree of the approximation can be adjusted with the deg parameter. We compare the result
with Maxima.
>x:=linspace(0,pi,100); y:=mxmidgl("sin(x)*y",x,1); y[-1]
~7.3890560989303,7.389056098931~
>plot2d(x,left(y));
>:: ode2(diff(y,x)=sin(x)*y,y,x); sol := ic1(%,x=0,y=1)
1 - cos(x)
y = %e
>mxmeval("rhs(sol)",x=pi)
7.389056098931

This can be used for exact inclusions of integrals. We compute the Gau normal
distribution.
Example:

>0.5+mxmiint("1/sqrt(2*pi)*exp(-x^2/2)",0,2)
~0.977249868051802,0.97724986805184~
>normaldis(2)
0.9772498730435

11.2.

ITERATION AND RECURSION

145

>xnormaldis(2)
0.9772498680518

Further Information
heun

11.2

Alternative to the Runge procedure.

Iteration and Recursion

For recursive sequences, Euler has the functions iterate and sequence. The most elementary form is iterate, which iterates a recursive sequence
xn+1 = f (xn )
starting from some point x0 until convergence occurs. Convergence is checked with the internal
epsilon. If the iteration cannot nd a xed point, you will have to stop it with the Esc key.
Alternatively, you can enter a maximal number of iterations. In this case, the function returns
all xi so far. The function will work for complex, and even for interval iteration, as long as f is
a contracting function and the iterations starts close enough.
>iterate("cos(x)",1)
0.7390851332157
>iterate("cos(x)",1+I)
0.7390851332157+0i
>iterate("cos(x)",~0.7,0.8~)
~0.7390851332146,0.739085133216~
>iterate("(x+2/x)/2",1,5)
1.5
1.416666666667
1.414215686275
1.414213562375
1.414213562373

can also handle sequences of vectors. In this case, a function is better than an expression.
Example: We iterate the arithmetic geometric mean
p
a +b
an+1 = an bn ; bn+1 = n n :
2
iterate

>function agm(v) := return [sqrt(v[1]*v[2]),(v[1]+v[2])/2]


>iterate("agm",[1,2])
1.456791031047
1.456791031047

146

CHAPTER 11.

ALGORITHMS IN EULER

A more exible recursive function is sequence. It can handle recursions of the form
xn = f (x1 ; : : : ; xn 1 ; n):
iterate returns a row vector with the sequence elements. Make sure, enough start values are
provided.
>goodformat(6,2);
>sequence("x[n-1]+x[n-2]",[1,1],10) // Fibonacci numbers
1
1
2
3
5
8
13
21
34
55
>sequence("n*x[n-1]",1,6) // factorials
1
2
6
24
120
720
>sequence("sum(x[n-4:n-1])/4",[1,2,3,4],10) // sliding mean
1
2
3
4
2.5 2.88 3.09 3.12
2.9
3
>longformat; v:=sequence("sum(x[n-4:n-1])/4",[1,2,3,4],1000); v[-1]
3

For sequences of vectors, you need a function, which computes the new column vector from the
previous column vectors stored in x.
11.3

Fast Fourier Transformation

Figure 11.2: Frequency Analysis with FFT

The Fast Fourier Transformation FFT is a technique, which evaluates trigonometric sums very
quickly in equidistant points. The inverse operation interpolates with Fourier sums. This is
useful for frequency analysis. For the optimal speed of the function the number of points should
be a power of 2, or at least have only small prime factors.
There is a notebook explaining the FFT in more detail.

11.3.

147

FAST FOURIER TRANSFORMATION

We generate values for the function sin(100x)+cos(200x), add noise, and analyze the
frequencies of the result. The analysis uses FFT to interpolate the values in the roots of unity.
The absolute values of the coecients then shows the contribution of the frequencies. However,
the relevant entries are only between frequency 1 and n=2, were n is the number of data.

Example:

>t:=linspace(0,2pi,1023); s:=sin(100t)+cos(200t)+normal(size(t));
>f:=abs(fft(s)); plot2d(f[1:512]);

There are some functions to generate and analyze sound. The following lines generate a sound,
and analyzes its frequencies using FFT, presenting a graphical representation.
>t=soundsec(5);
>s=sin(t*440)+sin(t*880)/2;
>analyzesound(s);

The sound can be played using playwave, or stored with savewave. Of course, sound can be
loaded into memory with loadwave too. All these functions work with a default sampling rate
of 22050 Hz. To analyze a sound with changing frequencies, use mapsound. This function will
use a windows FFT.
FFT can be used to fold two vectors. This is due to the fact, that folding two vectors is equivalent
to multiplying the Fourier transforms. Note that the signal vector is assumed to be periodic in
this case.
Example: Let us fold a vector with ( 1)k , such that the new vector contains the averages of
three neighboring points.
>k=(-1)^(1:1024);
>f=zeros(size(k)); f[1:3]=[1/3,1/3,1/3];
>k1=real(ifft(fft(k)*fft(f)));
>k1[1:3]
-0.3333333333333
0.3333333333333

-0.3333333333333

can also be handled by Euler, and there is a two dimensional FFT. Graphics can be
loaded into memory with loadpixels, and saved back with savepixels. The format is an RGB
matrix, containing one pixel per entry. To get the red, green and blue channels, use getred etc.
To create an RGB matrix from the channels, use putred etc., or rgb. To plot such an image into
the plot window, use plotrgb. Alternatively, insert the image into the notebook with insrgb.
Graphics

148

CHAPTER 11.

ALGORITHMS IN EULER

>red:=0:0.005:1; green:=red; blue:=random(cols(red),cols(red));


>M:=rgb(red,green,blue); plotrgb(M);
>insrgb(M);
>savergb(M,userhome()|"test.png");

11.4

Linear Programming

Euler has the Simplex algorithm for linear optimization. The function simplex maximizes
(max=1) or minimizes a linear target cT  x under the conditions
A  x  b; x  0:
Here, A is a matrix, each line containing one inequality.
Example: Maximize
5x + 8 y
under the conditions
x y
10 + 8  1;
x y
9 + 11  1;
x y
12 + 7  1;

and x; y  0.

>A:=[1/10,1/8;1/9,1/11;1/12,1/7]; b:=[1;1;1];
>x=simplex(A,b,[5,8],max=1); fracprint(x);
60/13
56/13

In the case of two variables, Euler can compute and plot the feasible set.
>xa:=feasibleArea(A,b);
>plot2d(xa[1],xa[2],filled=1,style="/",a=0,b=10,c=0,d=10);
>plot2d(x[1],x[2],add=1,points=1);

11.4.

LINEAR PROGRAMMING

149

Figure 11.3: Feasible Points and Solution

An integer solution can be found with intsimplex, or with the function ilpsolve from the
LPSOLVE package. This package must be loaded separately. The implementation in Euler is
due to Peter Notebaert.
>intsimplex(A,b,[5,8],max=1)
5
4
>load lpsolve
LPSOLVE package (ported by Peter Notebaert), and ilpsolve() routine.
The full documentation is available on
http://lpsolve.sourceforge.net/5.5/Euler.htm
>ilpsolve(A,b,[5,8],max=1)
5
4

Alternatively, it is possible to use \" or \=" in each or in all conditions. For this, a vector eq
must be given, containing 1, 0, or 1 for \", \=", or \" respectively. If the vector is only a
number, it is valid for all conditions. The default is 1.
Moreover, it is possible to get rid of the condition xi  0 for each or for all variables. The
functions simplex and intsimplex use a row vector restrict, containing ags 0 or 1, for
unrestricted or restricted variables. As above, a number can be used for all variables. The
default is 1.

150
Example:

as

CHAPTER 11.

ALGORITHMS IN EULER

We minimize 2x + y under the condition jxj + jyj  1. This condition can be written

1  x + y  1; 1  x
We solve the problem with and without restrictions.

y  1:

>A:=[1,1;1,1;1,-1;1,-1]; eq:=[-1;1;-1;1]; b=[1;-1;1;-1];


>A|eq|b
1
1
-1
1
1
1
1
-1
1
-1
-1
1
1
-1
1
-1
>simplex(A,b,[2,1],restrict=0)
-1
0
>simplex(A,b,[2,1],restrict=1)
0
0

Index
3d curves, 104
3d function plots, 102
3d grid plots, 102
3d line plots, 102
3d point plots, 102
3d surface, 103
adaptive, 141
anaglyph, 103
appending mode, 132
assigned parameter, 118
assigned parameters, 54
assignments, 32
badly conditioned, 135
binomial distribution, 131
boundary value problem, 142
brownian motion, 104
broyden, 105
by reference, 118
clipboard, 32
command line, 31
commands, 32
comment to a command line, 31
comments, 111
compatibility mode, 59
condition shortcut, 119
conditional branches, 119
contour plots, 107
current directory, 131
data, 131
default parameters, 109
di erential equations, 141
direct mode, 59
distribution functions, 131
double loop, 120

eigenvalues, 96
elementwise operation, 88
esc key, 31, 145
euler les, 37
evaluate a function, 122
evaluate an expression, 123
evaluation at compile time, 125
exact scalar product, 136
exact solutions, 137
expressions, 32
t, 146
fourier coecients, 124
function input state, 55
gau integration, 52
global variables, 117
graphics, 147
graphics window, 28
guaranteed inclusion, 144
help lines, 111
histogram, 129
inclusions of the solution, 137
interactive plots, 103
internal editor, 110
interval arithmetic, 79
interval newton method, 138
intial value problem, 141
levenberg-algorithm, 107
local variables, 117
loops, 120
map a function, 114
mark text, 32
matrix language, 88
muli-line commands, 32
151

152
multi-line functions, 109
multiple assignments, 33
multiplication of matrices, 92
nelder-mead, 105
newton algorithm, 105
normal distribution, 130
notebook, 28, 33
one-line functions, 109
open a le, 131
points in 3d, 104
random numbers, 129
read mode, 132
recursive functions, 121
recursive sequences, 145
red/cyan glasses, 103
residual iteration, 136
romberg method, 52
runge method, 141
semicolon parameters, 54, 123
several return values, 115
shue, 130
simplex algorithm, 148
simpson method, 52
singular values, 97
solid plots, 102
sort, 116
sound, 147
statistical tests, 133
status line, 30, 111
student-t test, 133
submatrix, 87
symbolic, 60
systems of equations, 105
tab key, 48
text window, 28, 31
user folder, 131
write mode, 132

INDEX

You might also like