F. Fassò.    University of Padova. 
Introduction to the use of Mathematica in Mathematics and Science. SoftSkills course for the PhD program in Mathematics
Lecture 1 (October 6, 2023)

1. A first look at Mathematica:  What can you do?  How?

NB : To open a section of this notebook click on the button, if present.
Otherwise, to open all the cells in a section, select them and press ALT + CGO  (or use the menu Cell->Grouping->Open All Subgroups).
To select all the cells of the notebooks, use  CTRL+A

1. What is Mathematica

Mathematica (nowdays: The Wolfram Language) is a programming language
– extremely versatile
–  extremely powerful
– with certain characteristics/limitations/tastes. E.g, is a functional language; is interpreted; ...

The basic difference from traditional programming languages (Fortran, C, Pascal, Basic,..) and from sofware packages such as Matlab is that these are (at least natively) oriented towards numerical computations. 
Mathematica, like other programs (Maple, MuPad, ...) can perform also symbolic computations.

Programs of this type are known with various names:
• Computer Mathematics Systems
• Computer Algebra Systems
• Symbolic Mathematics Software Packages
...

However, Mathematica is orientated both tho
• symbolic computations
• numerical computations

2. Input-Output

Start Mathematica
(details depend on operation system)

A window with a blank electronic sheet opens: it is called  notebook

The typical usage of  Mathematica
– uses the graphics interface provided by the notebook
– creates a file  *.nb   (called notebook )  that can be saved, updated, etc.

(Be careful: Mathematica does not create backup copies of the notebook; if necessary, save it)

A notebook is organized in cells, which are labelled “in” and “out” and are numered progressively:
– you enter your command in an “IN” cell
    use   SHIFT ENTER (or ENTER of the numerics keypad)
– Mathematica writes the result in an “OUT” cell 
Examples:

2+3

The result, written in the OUT cell, is memorized by Mathematica and accessible with the command 
      % cell number
(Shortenings: % calls the last OUT,  %%  the second to last, etc.)

%

3+%1

NB: 
1. Mathematica “reminds” all outputs until the session is terminated.
2. “;” suppresses the display of an output, not the assignment.

x=1;

%

x

Commands may be distributed on more lines (useful, for long expressions), but each line except the last must be left “open” (uncomputable)

x=2+
3

x=2
+3

The result, written in the OUT cell, is memorized by Mathematica and accessible with the command 
      % cell number
(Shortenings: % calls the last OUT,  %%  the second to last, etc.)

%

3+%1

To execute a sequence of commands:

1. Use different input cells

2. Use a single input cell, however writing them
    — on different lines 
     and/or 
    — separated by   ;   (I raccomend this: more readable; formatting might be lost).

x=2
y=2x

x=2;
y=2x

x=2; y=2x

3. Architecture of Mathematica: Kernel and Front End

Mathematica consists of two different programs:
● The Kernel, which executs all the computations
●  The Front End, which is the user interface

The Kernel is independent of the operating system  ->  portability of programs written in Mathematica
(except for round-off errors, which are platform-dependent)

The Front End is adapted to the various operating systems ->  small differences between different versions.

The user exchanges data with the Front End, which in turn exchanges them with the Kernel (which executes them)
                                      User ↔ FrontEnd ↔ Kernel

Fact :
     Every command entered in a Notebook is executed elsewhere (in the Kernel)
Corollaries:
    • It doesn’t matter at which point of the Notebook a command is written and executed
    • It’s only the order of executions of the commands that matters: the Kernel numbers them progressively.
    • The Kernel “remembers” an output  even if the corresponding cell (in the FrontEnd) is cancelled.
    • Pay attention to assignments such as  x = 3 because the Kernel remembers them!

• When you close Mathematica, the Kernel is terminated — and all its content is lost.
   Instead, a Notebook may be saved as a file and (re)executed once Mathematica is restarted.

•  Notebooks in use within a given Mathematica session use (by default) the same Kernel.
    => it does not matter in which of them you enter a command (they all “talk” to the same Kernel)

Example: execute the command
   x=8.1
then cancel the Input and Output cells and execute the command
    x

4. Symbolic computations 1: Operations on polynomials

To give a look at what, and how,  Mathematica does, let us begin with symbolic computations

4.1 Symbolic operations on polynomials

Expansions and factorization

Expansion of a polynomial into monomials, factorization of a polynomial
     Expand[ polynomial]
     Factor[ polynomial ]
     
NB: Here, “polynomial” is the expression of the polynomial

Expand[ (a+b+c)^3  ]

Factor[%]

Notes: 
          1. The arguments of functions are always delimited by square brackets     [ ]       (NOT  round brackets     (  ) )
               Examples:  Sin[x],  Log[3x+1], .....
               
          2. The names of all native commands in Mathematica are capitalized
          
          3.   (  )  group terms together (as in math) 
 
         4.   f[x]    is the same as     f@x   and    x//f

Example: compute cos(π)

(π  is “Pi”)

ArcSin@Cos[Pi]

Cos@Pi

Pi//Cos

Now compute arcsin(cos(π))  
(arcsin is “ArcSin”) 
You can: 

- rewrite everything

- go back to one of the previous cells and insert
      ArcSin[        ....   ]
      ArcSin@ ... 
      ...  // ArcSin

- copyand paste  one of the cells and do the same thing

ArcSin[Cos[Pi]]

ArcSin[Cos@Pi]

The previous expansions and factorizations were easy. 
Let’s try something more challenging:

(a+b+c)^20//Expand

%//Factor

Something even more challenging?

Expand[(a+b+c)^200]

If the output is very large, a shortened text is shown (this prevents long transfer times from the Kernel to the FrontEnd)

Factor@%

Note: An output may be very (even extremely) large
   • In such a case, if possible, Mathematica shows a shortened version.  
   • However, it might happen that the program becomes unresponsive (and even crashes).
   • If in doubt test all codes  with small numbers

 To reduce the size of the FrontEnd, it may also be useful 
   • suppress the output  with “:” 
   • cancel the output cell (results remains  memorized)

“Symplifying” polynomials and expressions

- Simplify[expression]
- FullSimplify[expression]

(((a+b+c))^5)-1 //Factor

Simplify[%]

%%//FullSimplify

((Sin[x])^2)+((Cos[x])^2)//Simplify

4.2 Solutions of equations (Solve, NSolve, FindRoot)

4.2.1 Exact solutions of algebraic equations

Roots of polynomials:
     Solve[polynomial == 0,variables]
or 
     Solve[polynomial1 == polynomial2, variables]

NB:   ==    not    =
(using “=” => disaster!)

Solve[x^3-2x+1==0,x]

What’s happening?  
We had assigned a value to the symbol x !

x

We need to cancel it:
       Clear[ symbols ]

Clear[x]

x

Solve[(x^3)-2x+1==0,x]

x/.%

x/.Solve[(x^3)-2x+1==0,x]

???

Solve returns a list of "substituting rules" : the list of values which, substituted to the variable, satisfy the equation.
(We will see laer how to work with lists and substitution rules)

The list of roots is obtained with
          x  /.  Solve[equazione, x] 
(“expression /.” means “replaces expression with what follows”)

x/.%

Might seem strange, but there is a logic.
E.g., we can work with all the roots at once:

To avoid re-computing each time the solutions, give it a name:

sol=Solve[(x^3)-2x+1==0,x]

x/.sol

Add 1 to all roots:

x+1/.sol

or compute their square

(x^2) /.sol

or check that they sastisfy the equation:

(x^3)-2x+1/.sol

???

Simplify[%]

Other example

Solve[(x^3)+(x^2)-1==0,x, Cubics->True]

???

In the last versions (beginning with v. 12), to prevent large outputs, by default  Mathematica does not give the complete expressions of the zeroes of polynomials of third and fourth degree if they involve roots.
Need ask Mathematica to do it:

Solve[(x^3)+(x^2)-1==0,x,Cubics->True]

Of course, solutions may be complicated

Solve[(x^4)-(x^3)+1==0,x,Quartics->True]

or Solve might not be able to compute them:

Solve[(pippo^7)-a (pippo^3)+1==0,pippo]

sol7=Solve[(x^7)-a (x^3)+1==0,x]

In such a case, however, Mathematica "knows something" on the solutions

((x^7)-a (x^3)+1)/.sol7

%// Simplify

and can evaluate them numerically  if the coefficients are numbers  ( sol7 /. a->2  e.g. )
          N[expression]  :  evaluates numericaly “expression”

N[Pi]

N[x/.sol7]

N[sol7/.a->2]

4.2.2 Numerical (=> approximate) solutions of algebraic equations

Search of numerical (=> approximated) roots of algebraic equations with numerical coefficients:
     NSolve[equation,variables]:

NSolve[(x^5)-(x^3)+1==0,x]

4.2.3 Numerical  solutions of (even non algebraic) equations

Search of numerical solution of an (even trascendental) equation, near a point:
      FindRoot[ equation , {variable , initialization point}  ]

NSolve[Sin[x]==(x/2),x]

FindRoot[ Sin[x]==(x/2),{x,1.5}]

Correct?
Plot the graphs of sin(x) and (x/2), e.g. in the interval  (-π, π)

Plot[ function,   {left limit point, right limit point} ]

 Plot[   {function1, function2,....}  ,   {left limit point, right limit point}   ]

Plot[ {Sin[x],x/2}  , {x,-Pi,Pi}, PlotStyle->{Red,Blue}  ]

Plot[ {Sin[x],x/2} ,{x,-Pi,Pi}]

Can we choose the color the two graphs ?

pl=Plot[   {Sin[x],(x/2)}  ,{x,-Pi,Pi},    PlotStyle->{Red,Blue}  ]

f[pl]

5. Symbolic computations 2: calculus (real functions)

Derivative of functions  (Reals)->(Reals)
      D[  function  ,  variable  ]
Indefinite integral
     Integrate[  function ,  variable  ]
     
(here, “function” is an expression containing the variable)

D[  a x, x]

D[a x, a]

D[ a x  ,x ]

Integrate[a x ,x ]

n-th derivative of function  (Reals)->(Reals)
      D[  function  ,  {variable,n}  ]

D[a (x^2),{x,2}]

Easy.
Something more complicate?

D[     ArcTan[    Log[x^Sin[x] ]  ] ,x]

Integrate[   ArcTan[Log[(x^(Sin[x]))]]  , x   ]

Can’t do it! 
To stop/quit the computation:
       ALT,        or        ALT.
or
      Menu “Evaluation” ->  “Abort evaluation”

Nevertheless, Mathematica can compute many (even difficult) integrals :

Integrate[  ((Cos[x] Log[x]+((Sin[x])/x))/(1+((Log[(x^(Sin[x]))])^2))), x]

Uhmm..... Is Mathematica cheating?
That it, does she remember that she had obtained this function as a derivative?
 
To doublecheck, quit the kernel, restart a new one, and try again:

To close the Kernel (without closing the notebook)
   • Quit[ ]
   • Menu “Evaluation” -> “Quit Kernel” -> “Local” (or the name of the Kernel you’re using, if different)

Quit[]

Integrate[((Cos[x] Log[x]+((Sin[x])/x))/(1+((Log[(x^(Sin[x]))])^2))),x]

(Why did Mathematica take longer this time?)

Partial derivatives of function  (((Reals))^m)-> (Reals)
      D[  function  ,  variable   ] 
    D[  function  ,  variable1, variable 2, ....}  ]

D[(x^2)+2x y + (y^2),x]

D[(x^2)+2x y +(y^2),x,y]

Jacobian matrix of function  (((Reals))^m)-> (((Reals))^n)
       D[  function   ,  {{ variables }}   ]      (n=1) 
      D[  { function1,..., functionn}  ,  {{variables}}   ]   (n>1)

D[(x^2)+2x y +(y^2),{{x,y}}]

6. Definition of functions

6.1 Functions in Mathematica

Extremely important: Mathematica is a functional language

Functions can be defined in different ways
The basic one is
    f[x_] := expression
This specifies that “f” is the function that trasforms its argument into “expression”

f[x_]:=(x^2) - 2(x^3)

f[2]

f[y]

f[pippo]

f[I]

NB: in the definition of a function
        the argument “x” is a symbol and must be followed by _ (“blank”)
        use    :=     
(or else  = ; the difference will be explained later)

Functions of more variables:
    f[x1_, x2_ , .... , xn_ ] :=  ....

Functions are not only numerical.  (Basic for functional programming)

(x^3)

Example

f[x_,y_]:= (x^3)+2y (x^2)+x -y

df=D[f[x,y], {{x,y}} ]

cp=Solve[df=={0,0},{x,y}]

f[x,y]/.cp

hf=D[ df, {{x,y}}]

hf//MatrixForm

hf/.cp

Eigenvalues[{{-(5/(Sqrt[2]))+3 (Sqrt[2]),2 (Sqrt[2])},{2 (Sqrt[2]),0}}]//N

cp//N

Plot3D[f[x,y],{x,-2,2},{y,-2,2}]

l

Lecture 2

Primi Esempi

Esercizio: scrivere una funzione che prende come argomento una funzione R->R (data come espressione contenente la variabile “x”) e ne fa il grafico nell’intervallo 0 < x < 1

x//Clear

pl[expr_] := Plot[expr, {x, 0, 1}]

Prova:

pl[ Sin[x] ]

Esercizio: scrivere una funzione  
                           pl(expr,a,b)
che fa il grafico della funzione di x la cui espressione e` expr nell’ intervallo a < x < b con a e b qualunque

pl[expr_,a_,b_Automatic:2]:=Plot[expr,{x,a,b}]

pl[(E^(x-1)), -3]

Possiamo usare lo stesso simbolo (nome: “pl”) per le due funzioni? 
Sì, perché hanno un diverso numero di argomenti.

Per chiedere a Mathematica cosa è un simbolo “symb”
     ? symb

?pl

pl

Quando si esegue una funzione, Mathematica
• sostituisce l'argomento alla "x" che appare nell'espressione al secondo membro della definizione    f[x_]:=....   
• ed eventualmente fa dei conti e delle semplificazioni

Esempio:  se si definisce
    f[u_] := (Sqrt[(u^2)])       ( Sqrt[u^2] )
quale sarà il risultato di  f[2] ?  E di  f[x]   o di   f[gianni] ?

f[u_]:= Sqrt[ (u^2) ]

f[2]

f[x]

Perche` non semplifica?
Possiamo forzarlo?

FullSimplify@%

No.
È ragionevole?

(Sqrt[(u^2)]) =  u    solo se  u  è un reale positivo.
Se non ha questa informazione sull’argomento, Mathematica non fa la semplificazione.

Assunzioni

Dobbiamo dire a Mathematica che l’argomento è un reale positivo, affinche faccia la semplificazione.
Come si fa?

Refine[ expr ,  condizione   ]
valuta  expr  assumendo vera la condizione
       Assuming[    condizione ,  Simplify[ expr ]   ]
semplifica  expr  assumendo vera la condizione (fra le altre cose, Simplify prova a usare Refine)

Refine[f[x],x<0]

Assuming[x<0, Simplify@f[x]]

Ruolo di _ nella def. delle funzioni

Attenzione: non dimenticare il _ nella definizione di una funzione, se no la funzione  è definita solo se l’argomento è esattamente  x .

Clear[g]

g[x]:=(x^2)-(x^3)

g[x]

g[1]

x=1

g[x]//Trace

Naturalmente, si può sfruttare (positivamente) questo fatto per assegnare particolari valori ad una funzione

Esercizio:  Definire la funzione  f  che ha valori
    f(x) =   ((sin(x))/x)  se x+ ≠ 0
    f(x) =   1  se x+ = 0
(senza usare un “If” o simili)

f[x_]:=((Sin[x])/x)

f[0]

f[0]:=1

?f

f[0]

oppure anche   f[0] = 1 (poi si capirà)

Definizioni iterative di funzioni

Solo un esempio : il fattoriale

f[0]=1;
f[n_]:=f[n-1]n

f[3]//Trace

È efficiente?

f[230]

Come lavora?

f[3]//Trace

Clear[f]

8. Help

Ci sono due help:
•  breve descrizione di un comando (Dall’INPUT :  ?comando)
•  manuale (con descrizione di tutte le funzioni, tutorials, e altro)
   ••  o dal MENU  “Help”  
   ••  o con  F1  (anche sulla parola)
   ••  o da “i” sul menu interattivo

Esempio : chiediamo aiuto per il comando “Expand”

?Expand

Expand

(dal menù interattivo, anche prima di aver scritto tutto il comando)

9. Formule “eleganti”  (= leggibili meglio!) (in Standard Form)

L'input si può rendere un po' più elegante con l'uso di apici, pedici, frazioni su due livelli, simboli greci, etc.
Vi si accede:
• da una palette (dal Menu Palettes)
• con key shortcuts, che sono molti comodi:

Esempi di key shortcuts:
    Sqrt[ ]   ->   (Sqrt[□])               (CTRL 2)
       x/y       ->   (x/y)                 (CTRL /)
       x^3       ->   (x^3)                  (CTRL  6)
            α                                       ( ESC a ESC )

Esercizio: scrivere, usando solo la tastiera
η ,     (Sqrt[4 β])  ,    (x^(3α))  ,   (5/3)   ,     (((((Sqrt[x+(x^2)])/(2-x))))^67)