Professional Documents
Culture Documents
An Introduction
Rene Grothmann
March 2010, Euler Version 9.2
Contents
Preface
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.1
3.2
3.3
3.4
3.5
3.6
3.7
Elementary Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Numerical Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Denition of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 Maxima
4.1
4.2
4.3
4.4
4.5
4.6
5 Data Types
5.1
5.2
5.3
5.4
Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Intervals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.1
6.2
6.3
6.4
6.5
6.6
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.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
11.1
11.2
11.3
11.4
Index
Dierential 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
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 dierent 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.
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 innite 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.
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
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.
>:: 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
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) dened 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 dierentiate, 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.
mxmsolve
>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
>:: 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 dene 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 denitions are separate. Both worlds can exchange, but not share data.
It might be more
exible to set the function in an expression rst, then dene it in either tool.
We suppress the output of the function denition 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.
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:
This is the x value, where the parabola p(x) has derivative 1. Now, we need p(x) = 1
this value.
at
1
[a = -------]
4 b - 4
With this knowledge, we dene 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
>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.
[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])
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.
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 dene 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
1.5.
1.5
23
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.
: 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:
24
CHAPTER 1.
Figure 1.3:
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
1.5.
25
>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.
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 dierent 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
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
>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
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.
The advantage of such a simple interface is that it is not complicated to learn. The disadvantage
is that it does not oer 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
graphics window can be exported in various formats. Either use the menu, or the functions
savepng, savesvg, saveps.
Further Information
TAB key
2.4
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 denitions 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
Syntax
>(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
2.6
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
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 aects Maxima too. The Maxima process ends,
and starts again.
2.7.
35
Further Information
Open Notebook
Open User Notebook
Open Introduction
Print Graphics
2.7
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
dierent.
>help sinh
function sinh ()
Function in file : functions
...
plotdf
2.8.
37
EULER FILES
Further Information
list text
help text
type text
2.8
Euler Files
If you want to develop longer and more complicated programs, it becomes useful to put all
function denitions 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 denition can be interpreted with one stroke of the return key.
2.8.
39
EULER FILES
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.
The external editor works with the load command too. But it cannot edit function denitions,
or command lines. The default external editor is JE, a Java based editor, which is installed
with Euler. However, you can congure 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
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.
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 denition
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 dened, even for negative numbers. Other powers of
negative numbers are not dened.
>(-2)^3
-8
>0^0
1
>(-1)^(1/2)
Illegal argument for ^
Error in ^
error in :
(-1)^(1/2)
^
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
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.
>shortformat; 1/3
0.333333
>fracformat; 1/3
1/3
>longformat;
>fracprint(1/3)
1/3
There are some special formats, and even user dened 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 oers 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
Further Information
demos format
degformat(flag)
degprint(x)
: 2^1000
epsilon
a =b
3.3
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
46
CHAPTER 3.
>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 specic name use listvar
string. Many variables are predened 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 dierent 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:
How many minutes takes the light from sun to earth on average.
>AU$/c$/min$
8.316746396769
To print a number in a specied 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
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 dened 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
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 specic 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.
>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
>help plot2d
3.6
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.
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 dierentiation. 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
In principle, numerical dierentiation is not very accurate. Maxima should be used for dierentiation.
>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
54
3.7
CHAPTER 3.
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 dened 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:
More complex Euler functions can be dened 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 denition.
>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.
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:
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 denition visible. It does indeed contain the correct
expression.
3.7.
DEFINITION OF FUNCTIONS
57
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.
Chapter 4
Maxima
4.1
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
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
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 \innite" arithmetic for integers and fractions. It will keep all digits of a
4.1.
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 dierent 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
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 simplication hints can be given, like
ratsimp, which simplies 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.
63
Trigonometric simplication 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
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
4.3.
65
MAXIMA FUNCTIONS
Maxima uses functions either as verbs or nouns. The dierence is, that verbs evaluate, and
nouns do not. To enter dierential equations, we must use the dierentiation 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
Maxima Functions
In Maxima we can dene 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 denition. 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 denition 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
The compatibility mode simply adds to evaluate the expression. Conversely, stops the
evaluation of the expression, which is sometimes useful, e.g., when dening dierential equations.
>:: diff(x^x,x)
d
x
-- (x )
dx
4.3.
67
MAXIMA FUNCTIONS
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:
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
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.
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 dened 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 specied 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 dening 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 denition of Euler functions.
>expr:="x^2";
>:: diff(@expr,x)
2 x
70
CHAPTER 4.
MAXIMA
Another practical method is to use Maxima functions in Euler. We can get an expression in
x for Euler, even if we used a dierent variable name in Maxima. Note that we use mxm to
evaluate a complete function denition 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 dene
the function in Euler. This is very easily done by calling Maxima at compile time. In the
denition 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 denition 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 dene 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
0 ]
]
1 ]
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
a
b
x= ; y=
c
c
which yields a2 + b2 = c2. Eectively, 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.
2
2
q - p
------2
2
q + p
74
CHAPTER 4.
MAXIMA
The solution is
a = 2pq; b = q 2
p2 ; c = q 2 + p2 :
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 dierence, 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
dierences of the compatibility mode and the direct mode in the following list.
Further Information
>::...
>:...
, and ;
; and $
|
,
:=
:
The main dierences 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.
75
Variables are set dierently 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 denition 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 dierent 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:
Example:
~19.3,19.8~
x2[a;b]
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 dierentiate 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
84
CHAPTER 5.
DATA TYPES
Chapter 6
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.
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
1
1
2
2
3
3
1
1
2
1
3
1
>v_1
6.1.
87
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
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
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
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
CHAPTER 6.
1
4
6
4
1
0
1
5
10
10
5
1
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
Example:
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
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);
92
CHAPTER 6.
Example:
How many prime numbers are less than n? And which of them have the form m2 +1?
Further Information
max(A),min(A)
totalmax(A),totalmin(A)
extrema(A)
sort(v)
6.3
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.
>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
0.0684755
Example:
96
CHAPTER 6.
6.5
Eigenvalues
>shortformat; A:=[1,2;2,1]
1
2
6.5.
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.
>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
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
100
CHAPTER 6.
Chapter 7
3D Plots
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.
>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);
Solid plots
7.2.
103
All plots can be drawn as anaglyph plots. To view this properly, you need red/cyan glasses.
The 3D eect 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 dened as mapping, would not need this. Then it is a bit faster
to swithc the mapping o with maps=0. This has no eect, 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.
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.
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);
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
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.
105
7.3
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.
106
CHAPTER 7.
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 dene 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
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
108
CHAPTER 7.
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 denition
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
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 denition 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
The map keyword in the denition 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 denition 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 dene 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.
sinctest
>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-dened 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 denitions 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)
^
8.2.
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-dened 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.
Redening built-in functions must be done with care. The following redention 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
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
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 dierent 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 dene it using map. But we do not want to map f to the polynomial coecients,
of course.
8.3.
115
The quick computation of Chebyshev polynomials uses dierent algorithms for x < 1,
1; 1] and x > 1. Note, that the following function is already contained in Euler.
Example:
x2[
8.3
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
Example:
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 dierence, 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
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:
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
Further Information
and, or
&&, ||
error(String)
index
8.6
Vector Parameters
Often a function requires a vector of specic 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
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
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 dened 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)
Example:
8.8.
125
>:: integrate(x^2*cos(3*x),x,-%pi,%pi)/%pi
4
- 9
8.8
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 denition 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 dened. 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 dene functions for derivatives. The Newton method requires a
function, which returns the Jacobian of a function. We can dene 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
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 eective.
8.9
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 dierent 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 dene 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 denition 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.
>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
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
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
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% condence interval.
normal distribution
9.3.
131
>~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.
It is often necessary to read and write data to external les. Euler supports this with a lot of
functions on dierent 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 eective 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
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
134
CHAPTER 9.
STATISTICS
Chapter 10
Exact Arithmetic
10.1
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
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
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).
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
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 ).
139
140
CHAPTER 10.
EXACT ARITHMETIC
Chapter 11
Algorithms in Euler
11.1
Differential Equations
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 dierential 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
>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
Euler can plot the direction eld of a dierential 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 dierential 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 denition 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 dierential 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.
145
>xnormaldis(2)
0.9772498680518
Further Information
heun
11.2
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
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
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
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
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
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:
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
dierential 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