# Comments in Maxima

/* i is a variable of interest */  i : 12;

/* Comments /* can be nested /* to any depth */ */ */  1+uvt;

# Example code

sum:0; /* initialize */
for i: 1 step 1 thru 10 do
sum : sum + i ;/* accumulate */
print(sum); /* output */;

# Excercise

(i)

sum:0;
for i:1 step 1 thru 100 do
sum:sum+i;
print(sum);

(ii)

sum:0;
for i: 2 step 2 thru 2000 do
sum:sum+i;
print(sum);

(iii)

sum:0;
for i: 1 step 2 thru 2000 do
sum:sum+i;
print(sum);

(iv)

for n: 1 step 1 thru 5 do
wxplot2d(sin(n*x),[x,-%pi,%pi]);

# Branching

Formal syntax

user:17$
if(user<18) then
print ("User is 18 or younger")
else
print ("User is older than 18")$

Relational Operators

if(1< 2)then
print("I like Maxima")
else
print("I like Mathematica")$

if(1 >= 2) then
print("I like Maxima")
else
print("I like Mathematica")$

Logical Operators

if ((1 < 2)and(2 < 3)) then
print("I like Maxima")
else
print("I like Mathematica")$

if ((1 < 2)and(2 > 3)) then
print("I like Maxima")
else
print("I like Mathematica")$

More complex if-else statements

score:98;

if (score >=90) then
print("A")
elseif ((80 <= score) and (score < 90)) then
print("B")
elseif ((70 <= score) and (score < 80)) then
print("C")
elseif ((60 <= score) and (score < 70)) then
print("D")
else
print("F");

Omiting ending else in if-else

if (1 = (2 + 4 + 6)/(6 + 4 + 2)*(2-1)) then
print("You are welcome");

if (1 = (2 + 4 + 6)/(6 + 4 + 2) * 2) then
print("You are welcome");

f(x):= if (x < 0) then
0
else if (0 <= x) and (x < 1) then
x
else
1;

Functions and if statements

f(x):= if (x < -5) then
(x+5)^2
else if (-5 <= x) and (x < 0) then
(x+5)/2
else if (0 <= x) and (x < 5) then
(-x+5)/2
else
(x-5)^2;

plot2d(f(x),[x,-10,10]);

Excercise 1

n:10;
fac:1;
for i: 1 step 1 while(n>1) do
block(
fac:fac*n,
n:n-1
);
print(fac)$

10!;

x:1$
y:0$
z:2$
for i:1 step 1 while((x-y)<=0 and (x-y)<5) do
block(
y:z*x,
x:y+z,
z:z+1
);
print(x,y,z)$

Excercise 2

sol1: ode2('diff(y,x)+y=x, y, x);

solinitial:ic1(sol1, x=0, y=1);

y(x):=%e^(-x)*((x-1)*%e^x+2);

y(1/5),numer;

y(2/5),numer;

y(3/5),numer;

y(4/5),numer;

y(5/5),numer;

y

f(x,y):=x-y$
x0:0$
y0:1$
xend:1$
steps:5$
h:(xend-x0)/steps$
x:x0$
y:y0$
for i: 1 step 1 while(i<=steps) do
block(
y:f(x,y)*h+y,
x:x+h,
print(x,y)
);

f(x,y):=x+2*y$
x0:0$
y0:0$
xend:1$
steps:4$
h:(xend-x0)/steps$
x:x0$
y:y0$
for i: 1 step 1 while(i<=steps) do
block(
y:f(x,y)*h+y,
x:x+h,
print(x,y)
);