Escolar Documentos
Profissional Documentos
Cultura Documentos
5
c
/
,
Outros atalhos interessantes so para insero de letras gregas. Usa-se a sequncia Esc letra Esc e automaticamente o Mathematica
converte a letra convencional em sua equivalente grega. Por exemplo Esc a Esc ( a , sem os espaos) resulta em o
Para expresses mais longas, o mesmo tipo de escrita do Excel vale, ou seja 1+(2/(3+5*3))
Exerccio: Escrevas as 10 primeiras letras gregas (correspondentes ao alfabeto latino).
ApresentaoSENC.nb 13
Clculos Bsicos
O Mathematica utiliza o ponto como demarcador de casas decimais.
0.001;
0, 001;
Note o smbolo de erro de sintaxe direita!
Para adio utiliza-se o sinal de +, para subtrao o -, para diviso a / e para o produto entre escalares pode-se utilizar *. Colocar em
sequncia tambm funciona quando um dos termo simblico:
a = 10;
2 + a
2 a
Quando no se est fazendo multiplicao simblica, basta dar um espao entre os termos que se pretende multiplicar. Por exemplo,
1*3 pode ser calculado como 1 espao 3. Automaticamento o Mathematica transforma o espao dado no simbolo de cruz:
10 2
Para potenciao pode-se utilizar o sinal ^.
Exerccios: Calcular
2 + +3 + 5 5^3/
,5
6
- 34 450 t 4!
2 3 4 5 6 7 8 9 10 t 2
5
14 ApresentaoSENC.nb
Listas, Vetores e Tensores
Em qualquer programa cujo objetivo desenvolver clculos interessante que se possa contruir listas, vetores e tensores.
No Mathematica isso muito simples. As listas e vetores so introduzidos entre chaves e com elementos separados por vrgulas:
lista = 1, 2, 3, 4, 5, 6;
A funo Dimensions[] permite avaliar as dimenses dos elementos inseridos
? Dimensions
Dimensions#expr' gives a list of the dimensions of expr.
Dimensions#expr, n' gives a list of the dimensions of expr down to level n. >
Dimensions#lista'
6
Para um tensor o mesmo se aplica:
tensor = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;
Dimensions#tensor'
2, 2, 3
ApresentaoSENC.nb 15
Listas, Vetores e Tensores
H algumas matrizes de interesse na teoria de algebra linear. Por exemplo, considere a matriz identidade.
? IdentityMatrix
IdentityMatrix#n' gives the nn identity matrix. >
IdentityMatrix#5'
interessante visualizar matrizes em suas formas tradicionais. Para tal, basta utilizar o comando MatrixForm[].
MatrixForm#IdentityMatrix#5''
A forma de sada de uma expresso tambm pode ser determinada pelo atalho // seguido da funo que se vai aplicar:
IdentityMatrix#5' ss MatrixForm
16 ApresentaoSENC.nb
Listas, Vetores, Tensores
A gerao de listas pode ser manual, conforme mostrado anteriormente, ou automtica. Um dos mais importantes comandos do Math-
emtica a funo Table[].
? Table
Table#expr, imax' generates a list of imax copies of expr.
Table#expr, i, imax' generates a list of the values of expr when i runs from 1 to imax.
Table#expr, i, imin, imax' starts with i = imin.
Table#expr, i, imin, imax, di' uses steps di.
Table#expr, i, i
1
, i
2
, ' uses the successive values i
1
, i
2
, .
Table#expr, i, imin, imax, j, jmin, jmax, ' gives a nested list. The list associated with i is outermost. >
Por exemplo, quero listar os primeros 10 nmeros naturais ao quadrado:
Table#n^2, n, 1, 10'
O mesmo raciocnio se aplica a matrizes e tensores. Por exemplo, para mostrar os 5 primeiros mltiplos dos 4 primeiros nmeros
naturais:
Table#i^j, i, 1, 4, j, 1, 5' ss MatrixForm
Exerccio: Gere uma matriz 3x5 em que cada elemento o dobro do nmero da linha menos o
nmero da coluna em que est.
ApresentaoSENC.nb 17
Produto Escalar e Vetorial
Quando se est estudando lgebra linear, as operaes de produto escalar e vetorial se tornam importantes. Tais operaes podem ser
alcanadas por meio das funes Dot[] e Cross[]. Tais funes tambm podem ser substituida pelo ponto e pelo atalho Esc cross Esc.
a = 1, 2, 3;
b = 4, 2, 6;
Para o produto escalar:
a.b
++ou+/
Dot#a, b'
Para o produto vetorial:
ab
++ou+/
Cross#a, b'
Exerccio: Calcule o Produto escalar e vetorial entre as bases do espao vetorial 3D i, j e k.
18 ApresentaoSENC.nb
Determinante e Trao
Pode-se calcular o determinante de uma matriz no Mathematica por meio da funo Det[].
? Det
Det#m' gives the determinant of the square matrix m. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
Det#matriz'
matriz = 1, 2, 3, 4, 11, 6, 7, 8, 9;
Det#matriz'
Pode-se tambm determinar o trao de uma dada matriz por meio do comando Tr[].
? Tr
Tr#list' finds the trace of the matrix or tensor list.
Tr#list, f ' finds a generalized trace, combining terms with f instead of Plus.
Tr#list, f , n' goes down to level n in list. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
Tr#matriz'
Exerccio: Calcule o determinante e o trao da matriz identidade 10x10
ApresentaoSENC.nb 19
Transposta e Inversa
Pode-se tambm facilmente encontrar a matriz transposta de uma referida matriz por meio da funo Transpose[].
? Transpose
Transpose#list' transposes the first two levels in list.
Transpose#list, n1, n2, ' transposes list so that the k
th
level in list is the nk
th
level in the result. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
Transpose#matriz'
A matriz inversa tambm pode ser facilmente encontrada por meio do comando Inverse[].
? Inverse
Inverse#m' gives the inverse of a square matrix m. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
Inverse#matriz'
matriz = 1, 2, 3, 4, 11, 6, 7, 8, 9;
Inverse#matriz'
Exerccio: Crie uma matriz 4x4 cujos elementos so o nmero da linha ao quadrado menos a raiz
cbica do nmero da coluna. Encontre a transposta e a inversa dessa matriz
20 ApresentaoSENC.nb
Rank e Autovalores
O rank de uma matriz pode ser facilmente determinado por meio da funo MatrixRank[].
? MatrixRank
MatrixRank#m' gives the rank of the matrix m. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixRank#matriz'
Com a mesma simplicidade, autovalores para uma dada matriz podem ser calculados por meios dos comandos Eigenvalues[].
? Eigenvalues
Eigenvalues#m' gives a list of the eigenvalues of the square matrix m.
Eigenvalues#m, a' gives the generalized eigenvalues of m with respect to a.
Eigenvalues#m, k' gives the first k eigenvalues of m.
Eigenvalues#m, a, k' gives the first k generalized eigenvalues. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
Eigenvalues#matriz'
Exerccio: Crie uma matriz 6x6 cujos elementos so a soma do nmero de sua linha e coluna.
Encontre o rank e os autovalores dessa matriz.
ApresentaoSENC.nb 21
Autovetores e Matriz Reduzida
Auto vetores so tambm de fcil obteno por meio da funo Eigenvectors[].
? Eigenvectors
Eigenvectors#m' gives a list of the eigenvectors of the square matrix m.
Eigenvectors#m, a' gives the generalized eigenvectors of m with respect to a.
Eigenvectors#m, k' gives the first k eigenvectors of m.
Eigenvectors#m, a, k' gives the first k generalized eigenvectors. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
Eigenvectors#matriz'
Quando se quer encontrar a matriz reduzida de uma dada matriz, basta utilizar o comando RowReduce[].
? RowReduce
RowReduce#m' gives the row-reduced form of the matrix m. >
matriz = 1, 2, 3, 4, 5, 6, 7, 8, 9;
RowReduce#matriz'
Exerccio: Calcule os autovetores a forma reduzida da matrix
1 1 0
1 5 4
3 2 9
22 ApresentaoSENC.nb
Definies e Atribuies
H no Mathematica duas maneira principais de definir um dado smbolo. Quando se utiliza o sinal de igualdade:
? =
lhs = rhs evaluates rhs and assigns the result to be the value of lhs. From then on, lhs is replaced by rhs whenever it appears.
l1, l2, =r1, r2, evaluates the ri, and assigns the results to be the values of the corresponding li. >
a = 20;
a
Por outro lado, ao utilizar a combinao := subentende-se outro significado:
? :=
lhs := rhs assigns rhs to be the delayed value of lhs. rhs is maintained in an unevaluated form. When lhs appears, it is replaced by rhs, evaluated afresh each time. >
ApresentaoSENC.nb 23
Definindo funes
A diferena entre = e := se mostra determinante na definio de funes. Para definir uma funo de uma dada variavel x, utiliza-se a
estrutura
f#x_' := Cos#Pi + x' + Exp#-x^3' + Log#2 + x'
Toda e qualquer funo no Mathematica; seja interna, seja definida, ter seus argumentos entre colchetes.
Ao definir uma funo, a varivel deve ter o sublinhado seguindo seu smbolo. Isso mostra ao programa que aquele valor muda e o
argumento da funo.
Para calcular o valor de f, basta chamar a funo
f#3'
f#9'
f#-1'
Exerccio: Defina a funo l(x)=
c
-x
x!
x
e calcule seu valor em x = 10 e 20.
24 ApresentaoSENC.nb
Literal ou Numrico?
Como o Mathematica permite clculos tanto literais quando numricos, em geral respostas exatas (literais) so fornecidas. Para obter
um valor numrico, basta utilizar a funo N:
? N
N#expr' gives the numerical value of expr.
N#expr, n' attempts to give a result with n-digit precision. >
N#f#3''
N#f#3', 110'
N#f#3', 800'
Ao utilizar o ponto na representao de um nmero, automaticamente o Mathematica retorna valores numricos
f#3.'
ApresentaoSENC.nb 25
Constantes Matemticas Implementadas
H no Mathematica um grande nmero de constantes implementadas, entre elas:
Nmero de Euler:
E;
Constante de Euler-Mascheroni:
EulerGamma;
O nmero Pi:
Pi;
A Razo Aurea:
GoldenRatio;
O Nmero complexo i:
I;
O nmero de radianos por grau (r/180):
Degree;
Exerccio: Quais os 100 Primeiros Dgitos de Pi? Quais os primeiros 50 dgitos do nmero de Euler?
26 ApresentaoSENC.nb
Um Pouco de Clculo: Sequncias
Caso se conheaa funo geradora da sequncia, seus termos podem ser obtidos por meio da funo Table[] j explicada anterior-
mente. Considere a sequncia cujos elementos tem forma a
n
= +1 + 1 s n/
n
Table#+1 + 1 s n/^n, n, 1, 10'
Pode-se determinar os termos de uma sequncia por meio de uma frmula recursiva. Para a sequencia de Fibonacci:
seq#0' = 0;
seq#1' = 3;
seq#n_' := seq#n' = seq#n - 1' - seq#n - 2' + 2;
Table#seq#n', n, 0, 10'
Nota-se a utilizao do truque seq[n_]:=seq[n]= para que o Mathematica guarde em seu kernel esse valor, no tendo que calcul-lo
novamente todas as vezes.
Exerccios: Implemente a sequencia de nmeros de Fibonacci. Mostre os 30 primeiros nmeros
dessa srie
ApresentaoSENC.nb 27
Um Pouco de Clculo: Sequncias
As somas parciais (do primeiro ao m-simo termo) podem ser obtidas por meio do comando Sum[] do Mathematica.
? Sum
Sum# f , i, imax' evaluates the sum
i=1
imax
f .
Sum# f , i, i
min
, imax' starts with i = i
min
.
Sum# f , i, imin, imax, di' uses steps di.
Sum# f , i, i1, i2, ' uses successive values i1, i2, .
Sum# f , i, i
min
, imax, j, j
min
, jmax, ' evaluates the multiple sum
i=imin
imax
j=jmin
jmax
f .
Sum# f , i' gives the indefinite sum
i
f . >
SomaParcial#m_' := Sum#1 s n!, n, 0, m';
SomaParcial#5'
28 ApresentaoSENC.nb
Um Pouco de Clculo: Sequncias
Por outro lado, o produto dos m-simos primeiro termos pode ser obtido por meio da funo Product[] do Mathematica.
? Product
Product# f , i, imax' evaluates the product
i=1
imax
f .
Product# f , i, imin, imax' starts with i = imin.
Product# f , i, imin, imax, di' uses steps di.
Product# f , i, i1, i2, ' uses successive values i1, i2, .
Product# f , i, imin, imax, j, jmin, jmax, ' evaluates the multiple product
i=imin
imax
j=jmin
jmax
f .
Product# f , i' gives the indefinite product
i
f . >
ProdutoParcial#m_' := Product#+1 + 1 s n/^n, n, 1, m';
ProdutoParcial#5'
ApresentaoSENC.nb 29
Um Pouco de Clculo: Sries
Ao somar os termos de uma sequncia podemos definir uma srie. Em especial, considere a srie da funo exponencial:
Sum#1 s n!, n, 0, Infinity'
O programa converte automaticamente sries em funes elementares e especiais.
H tambem a possibilidade de checar a convergncia de sries por meio da funo SumConvergence[].
? SumConvergence
SumConvergence# f , n' gives conditions for the sum
n
o
f to be convergent.
SumConvergence# f , n1, n2, ' gives conditions for the multiple sum
n1
o
n2
o
f to be convergent. >
Para a srie harmnica por exemplo:
SumConvergence#1 s n, n'
Para a srie harmnica alternante, por outro lado:
SumConvergence#++-1/^n/ s n, n'
30 ApresentaoSENC.nb
Fim do Primeiro Dia....
Dvidas?
ApresentaoSENC.nb 31
Um Pouco de Clculo: Limites
O clculo de limites extremamente facilitado por meio do Mathematica e sua funo Limit[].
? Limit
Limit#expr, x > x0' finds the limiting value of expr when x approaches x0. >
Assim, tem-se:
Limit#Sin#x' s x, x - 0'
Limit#+1 + x s n/^n, n - Infinity'
Limit#+1 - Cos#x'/ s x^2, x - 0'
Limit#Sin#o + x' s Sin#p + x', x - 0'
32 ApresentaoSENC.nb
Um Pouco de Clculo: Derivadas
O Mathematica permite a realizao de derivadas de toda ordem e tipo por meio da funo D.
? D
D# f , x' gives the partial derivative o f s ox.
D# f , x, n' gives the multiple derivative o
n
f t ox
n
.
D# f , x, y, ' differentiates f successively with respect to x, y, .
D# f , x1, x2, ' for a scalar f gives the vector derivative +o f s ox1, o f s ox2, /.
D# f , array' gives a tensor derivative. >
Assim, considere a funo:
g#y_' := y^2
Sua derivada ser:
D#g#y', y'
Para a funo f definida anteriormente
f#x'
D#f#x', x'
Exerccios: Calcule a derivada das funes Sin, Cos, Tan, Arctan
ApresentaoSENC.nb 33
Um Pouco de Clculo: Derivadas
Para uma derivada de ordem maior tem-se:
D#f#x', x, 2'
Para uma funo de vrias variveis:
j#x_, y_' := Cos#x + y' + Gamma#y' + Exp#x^y'
D#j#x, y', x'
Pode-se derivar em sequncia. Por exemplo, primeiro em y depois em x:
D#j#x, y', y, x'
Pode-se tambm realizar a derivao de funes com variveis literais:
D#Log#o + x' + +p^x/ + Tan# + +x^5/', x'
34 ApresentaoSENC.nb
Sries de Taylor
As sries de Taylor de uma funo esto intimamente relacionadas s suas derivadas. Por meio do programa Mathematica, por outro
lado, basta utilizar o comando Series[] para gerar a srie de Taylor de uma funo.
? Series
Series# f , x, x
0
, n' generates a power series expansion for f about the point x = x
0
to order +x x
0
/
n
.
Series$ f , x, x0, nx, y, y0, ny, ( successively finds series expansions with respect to x, then y, etc. >
Series#Cos#x' s x, x, 0, 10'
Series#Exp#x', x, 0, 10'
Series#Sin#x' s x, x, 0, 10'
Exerccio: Calcule a srie de Taylor at ordem 10 para as funes e
xsin+x/
e log(sinh(x)) em torno de
x=0
ApresentaoSENC.nb 35
Um Pouco de Clculo: Integrais
O Mathematica permite a realizao de integrais de toda ordem e tipo por meio da funo Integrate.
? Integrate
Integrate# f , x' gives the indefinite integral f d x.
Integrate# f , x, x
min
, xmax' gives the definite integral
xmin
xmax
f d x.
Integrate# f , x, xmin, xmax, y, ymin, ymax, ' gives the multiple integral
xmin
xmax
d x
ymin
ymax
d y f . >
Assim, considere a funo:
g#y_' := y^2
Sua Integral ser:
Integrate#g#y', y'
Para a funo h definida como:
h#x_' := Log#x' + x^2
Integrate#h#x', x'
36 ApresentaoSENC.nb
Um Pouco de Clculo: Integrais
Assim como no caso das derivadas, integrais de funes com variveis literais tambm podem ser calculadas.
Integrate#+x^o/ + Log#x^p', x'
Pode-se realizar integrais definidas tambm:
Integrate#Exp#-x^2' s ++Pi/^+1 s 2//, x, 0, Infinity'
Pode ser que a integral s exista em algumas circunstncias; nesse caso, o Mathematica retorna as condies de existncia:
Integrate#+x^+s - 1// + Exp#-x', x, 0, Infinity'
Um outro exemplo:
Integrate#+x^o/ + Exp#-p + x^', x, 0, Infinity'
Exerccio: Calcule a Integral da funo 1 + x
,
x
o
ApresentaoSENC.nb 37
E se a Expresso Ficar Longa e Complicada?
Caso a expresso avaliada fique muito longa e aparentemente mais complexa do que deveria, a funes Simplify e FullSimplify podem
ser utilizadas.
? Simplify
Simplify#expr' performs a sequence of algebraic and other transformations on expr, and returns the simplest form it finds.
Simplify#expr, assum' does simplification using assumptions. >
? FullSimplify
FullSimplify#expr' tries a wide range of transformations on expr involving elementary and special functions, and returns the simplest form it finds.
FullSimplify#expr, assum' does simplification using assumptions. >
D#Integrate#1 s +x^3 + 1/, x', x'
Simplify#'
FullSimplify#x Gamma#x''
38 ApresentaoSENC.nb
E se a Expresso Ficar Longa e Complicada?
possvel sujeitar as operaes de simplificao a consideraes:
Simplify#Sqrt#x^2''
Simplify#Sqrt#x^2', x > 0'
Simplify#Sqrt#x^2', x < 0'
Se, por outro lado, busca-se expandir ao mximo uma dada expresso (produtos de polinmios, por exemeplo), a funo Expand pode
ser utilizada.
? Expand
Expand#expr' expands out products and positive integer powers in expr.
Expand#expr, patt' leaves unexpanded any parts of expr that are free of the pattern patt. >
Expand#+1 + x + y/ +2 - x/^3'
Quando se quer fatorar uma expresso em produtos de termos, a funo Factor se torna til
? Factor
Factor# poly' factors a polynomial over the integers.
Factor# poly, Modulus > p' factors a polynomial modulo a prime p.
Factor# poly, Extension >a1, a2, ' factors a polynomial allowing coefficients that are rational combinations of the algebraic numbers ai. >
Factor$8 - 4 x - 6 x
2
+ 5 x
3
- x
4
+ 8 y - 12 x y + 6 x
2
y - x
3
y(
ApresentaoSENC.nb 39
Resolvendo Equaes
Em qualquer campo da cincia, o resultado buscado em geral obtido da soluo de uma equao. Por meio do comando Solve[], o
Mathematica proporciona a soluo numrica ou literal de equaes.
? Solve
Solve#expr, vars' attempts to solve the system expr of equations or inequalities for the variables vars.
Solve#expr, vars, dom' solves over the domain dom. Common choices of dom are Reals, Integers, and Complexes. >
Das algbricas mais simples: x^2+x-1 =0
Solve#x^2 + x - 1 = 0, x'
Literais: ox^2 + x+, =0
Solve#o + x^2 + p + x + = 0, x'
s transcendentes mais complexas: p
ox+
,x 5 = 0
Solve#p^+o + x + p/ - + x - 5 = 0, x'
40 ApresentaoSENC.nb
Resolvendo Equaes
Nota-se a funo solve busca solues analticas para as equaes. Caso se desejar saber apenas a soluo numrica, a funo
NSolve[] dever ser utilizada.
? NSolve
NSolve#expr, vars' attempts to find numerical approximations to the solutions of the system expr of equations or inequalities for the variables vars.
NSolve#expr, vars, Reals' finds solutions over the domain of real numbers. >
NSolve#x^5 - 2 x + 3 = 0, x'
NSolve#x^4 - Exp#-x' = 0, x'
Pode-se buscar apenas solues reais, por exemplo:
NSolve#x^5 - 2 x + 3 = 0, x, Reals'
ApresentaoSENC.nb 41
Resolvendo Sistemas de Equaes Lineares
Para resolver um sistema de equaes lineares, o comando LinearSolve[] de grande utilidade.
? LinearSolve
LinearSolve#m, b' finds an x that solves the matrix equation m.x ==b.
LinearSolve#m' generates a LinearSolveFunction#' that can be applied repeatedly to different b. >
Considere ento o sistema :
2 x + 3 y = 0
11 x 45 y = 1
LinearSolve#2, 3, 11, -45, 0, 1'
O comando Solve[] tambm pode ser utilizado, bastando inserir as equaes separadas por && (atalho para a funo And[]).
Solve#2 + x + 3 + y = 0 && 11 + x - 45 + y = 1, x, y'
++ou+/
Solve#And#2 + x + 3 + y = 0, 11 + x - 45 + y = 1', x, y'
Outra forma de utilizar o comando Solve[] inserir as equaes como uma lista:
Solve#2 + x + 3 + y = 0, 11 + x - 45 + y = 1, x, y'
42 ApresentaoSENC.nb
Resolvendo Sistemas de Equaes No-Lineares
Sistemas de equaes no-lineares podem ser da mesma forma resolvidas. Considere o sistema:
3 x
7
5 y
3
+ z = 0
11 x
6
4 y z
2
= 1
x + y + 3 z = 4
Solve#3 + x^7 - 5 + y^3 + z = 0, 11 + x^6 - 4 + y - z^2 = 1, x + y + 3 + z = 4, x, y, z'
ApresentaoSENC.nb 43
Resolvendo Sistemas de Equaes No-Lineares
Nesse caso o sistema no tem soluo analtica. Para obter a soluo Numrica utilizamos o NSolve[].
NSolve#3 + x^7 - 5 + y^3 + z = 0, 11 + x^6 - 4 + y - z^2 = 1, x + y + 3 + z = 4, x, y, z'
44 ApresentaoSENC.nb
Visualizando Resultados
H uma variedade de formas de visualizar resultados no Mathematica. A mais comum por meio das funes de plotagem:
? Plot*
System`
Plot Plot3Matrix PlotJoined PlotLayout PlotMarkers PlotRange PlotRangePadding PlotStyle
Plot3D PlotDivision PlotLabel PlotLegends PlotPoints PlotRangeClipping PlotRegion
A funo Plot pode ser usada para grficos 2D de funes:
? Plot
Plot# f , x, xmin, xmax' generates a plot of f as a function of x from xmin to xmax.
Plot# f1, f2, , x, xmin, xmax' plots several functions fi. >
Plot#x + Exp#-x s 10' + Sin#x', x, 1, 10'
ApresentaoSENC.nb 45
Visualizando Resultados
Pode-se plotar vrias funes ao mesmo tempo. Para tal, basta entrar com argumento para a funo Plot a lista de funes a ser
plotada. Para adicionar legendas, basta utilizar a opo PlotLegends Expressions.
Plot#Sin#x', Sin#2 x', Sin#3 x', x, 0, 2 Pi, PlotLegends - "Expressions"'
possvel preencher regies nos grficos por meio da Opo :
Plot#Sin#x' + x s 2, Sin#x' + x, x, 0, 10, Filling - 1 - 2'
46 ApresentaoSENC.nb
Controle Dinmico de Visualizao
Um dos mais interessantes recursos de visualizao do Mathematica a modificao dinmica pelo usurio de alguma plotagem. Tal
feito alcanado pela funo Manipulate
? Manipulate
Manipulate#expr, u, u
min
, umax' generates a version of expr with controls added to allow interactive manipulation of the value of u.
Manipulate#expr, u, umin, umax, du' allows the value of u to vary between umin and umax in steps du.
Manipulate#expr, u, uinit , umin, umax, ' takes the initial value of u to be uinit .
Manipulate#expr, u, uinit , ulbl, ' labels the controls for u with ulbl.
Manipulate#expr, u, u
1
, u
2
, ' allows u to take on discrete values u
1
, u
2
, .
Manipulate#expr, u, , v, , ' provides controls to manipulate each of the u, v, .
Manipulate#expr, cu >u, , cv >v, , ' links the controls to the specified controllers on an external device. >
Manipulate#Plot#Cos#p + x' + Sin#o + x' s +x/, x, 0, 2 + Pi, PlotRange - Full', o, 4, 0, 10, p, 2, 0, 10'
ApresentaoSENC.nb 47
Inserindo Grficos em Plotagens
Alm de plotar funes, o Mathematica tambm permite que sejam visualizadas figuras geomricas 2D e 3D. Para tal, a figura de inter-
esse deve ser gerada a partir do Comando Graphics, conforme mostra-se abaixo:
? Graphics
Graphics# primitives, options' represents a twodimensional graphical image. >
Como argumentos para a funo graphics tem-se, por exemplo
? Rectangle
Rectangle#xmin, ymin, xmax, ymax' is a twodimensional graphics primitive that represents a filled rectangle, oriented parallel to the axes.
Rectangle#xmin, ymin' corresponds to a unit square with its bottomleft corner at xmin, ymin. >
? Disk
Disk#x, y, r' is a twodimensional graphics primitive that represents a filled disk of radius r centered at the point x, y.
Disk#x, y' gives a disk of radius 1.
Disk#x, y, r, 01, 02' gives a segment of a disk.
Disk$x, y, rx, ry( gives an elliptical disk with semiaxes of lengths rx and ry, oriented parallel to the coordinate axes. >
? Arrow
Arrow#pt
1
, pt
2
' is a graphics primitive that represents an arrow from pt
1
to pt
2
.
Arrow#pt
1
, pt
2
, s' represents an arrow with its ends set back from pt
1
and pt
2
by a distance s.
Arrow#pt
1
, pt
2
, s1, s2' sets back by s1 from pt
1
and s2 from pt
2
.
Arrow#curve, ' represents an arrow following the specified curve. >
48 ApresentaoSENC.nb
Inserindo Grficos em Plotagens
? Circle
Circle#x, y, r' is a twodimensional graphics primitive that represents a circle of radius r centered at the point x, y.
Circle#x, y' gives a circle of radius 1.
Circle#x, y, r, 01, 02' gives a circular arc.
Circle$x, y, rx, ry( gives an ellipse with semi-axes of lengths rx and ry, oriented parallel to the coordinate axes. >
? Polygon
Polygon#pt
1
, pt
2
, ' is a graphics primitive that represents a filled polygon.
Polygon#pt
11
, pt
12
, , pt
21
, , ' represents a collection of polygons. >
Podem ser todos combinados em um nico comando Graphics:
Graphics#Thick, Green, Rectangle#0, -1, 2, 1', Red, Disk#', Blue, Circle#2, 0', Yellow, Polygon#2, 0, 4, 1, 4, -1',
Purple, Arrowheads#Large', Arrow#4, 3 s 2, 0, 3 s 2, 0, 0', Black, Dashed, Line#-1, 0, 4, 0''
ApresentaoSENC.nb 49
Inserindo Grficos em Plotagens
Pode-se combinar elementos gerados pelo comando Graphics com aqueles gerados pelo comando Plot por meio do comando Show.
? Show
Show#graphics, options' shows graphics with the specified options added.
Show#g1, g2, ' shows several graphics combined. >
Show#Plot#Cos#x', x, 0, 2 + Pi', Graphics#LightBlue, Disk#Pi, 0, 0.5', Red, Circle#1.5, 0'''
50 ApresentaoSENC.nb
Combinando Plotagens
Alm de Combinar plotagens e grficos, o comando show tambm permite reunir diferentes tipos ede plotagens:
Show#Plot#Cos#x', x, 0, 2 + Pi', ListPlot#Table#x, Cos#x', x, 0, 2 + Pi, 0.1', PlotStyle - Red''
data = RandomVariate#NormalDistribution#1, 3', 10^5';
Show#Histogram#data, 20, "PDF"', Plot#PDF#NormalDistribution#1, 3', x', x, -9, 9, PlotStyle - Thick''
ApresentaoSENC.nb 51
Programao em Mathematica
Assim como em qualquer outra linguagem de programao, o conhecimento das estruturas e lexico da Wolfram language so
necessrios. No Mathematica os comandos tradicionais como Do, If e While esto presentes, no entanto outros comandos como Nest,
NestWhile e Map foram introduzidos e so mais eficazes na escrita de um dado cdigo.
Haja vista o grande nmero de funes e funcionalidades implementadas no Mathematica, a gerao de cdigos em Wolfram Lan-
guage uma das mais importantes funcionalidades do programa.
Infelizmente um tratamento completo dessa funcionalidade foge do escopo do presente curso =(
Para que seja possvel visualizar a utilizao da programao em Mathemtica, alguns pequenos cdigos sero mostrados a ttulo de
exemplificao.
52 ApresentaoSENC.nb
Dividindo Tringulos
Dividir um tringulo em trs, tomando o centride como centro de diviso:
f#data_' := Module#data2, data2 = Subsets#data, 2';
Table#AppendTo#data2##i'', Mean#data'', i, 1, Length#data2''';
g#data_, n_' := If#n = 0, Graphics#EdgeForm#Dashed', White, Polygon#data'',
Graphics#Flatten#EdgeForm#Dashed', White, Map#Polygon#' &, Nest#Flatten#Map#f, ', 1' &, f#data', n - 1''''';
data = 0, 0, 0.5, Sqrt#3' s 2, 1, 0;
Manipulate#g#data, n', n, 0, 5, 1'
ApresentaoSENC.nb 53
Resolvendo a Equao De Adveco o
t
c +vo
x
c =0
Com o intuito de simplificar a criao de algortmos, apenas uma rotina foi criada, sendo possvel escolher qual a metodologia de cl-
culo ser utilizada. A opo nmero 1 se refere metodologia MDF com avano no tempo e centrada no espao; a 2, a metodologia
MDF avanada no tempo e atrasada no espao; a 3, a metodologia MDF avanada no tempo e avanada no espao; a 4 a metodologia
desenvolvida por Lax e, finalmente, a opo 5 se refere metodologia denominada Lax-Wendroff.
Needs#"PlotLegends`"';
MDFAdvecoExplcito#c0_, dominio_, subdivisoest_, subdivisoesx_, v_, passostempo_, opo_' :=
Module#At = passostempo s subdivisoest, Ax = +dominio##2'' - dominio##1''/ s subdivisoesx, Cr,
Clear#c';
Cr = v + At s Ax;
Which#opo = 1, c#n_, k_' := c#n, k' = c#n - 1, k' - Cr + +c#n - 1, k + 1' - c#n - 1, k - 1'/ s 2, opo == 2,
c#n_, k_' := c#n, k' = c#n - 1, k' - Cr + +c#n - 1, k' - c#n - 1, k - 1'/, opo = 3, c#n_, k_' := c#n, k' = c#n - 1, k' - Cr + +c#n - 1, k + 1' - c#n - 1, k'/,
opo = 4, c#n_, k_' := c#n, k' = +c#n - 1, k + 1' + c#n - 1, k - 1'/ s 2 - Cr + +c#n - 1, k + 1' - c#n - 1, k - 1'/ s 2, opo = 5,
c#n_, k_' := c#n, k' = c#n - 1, k' - Cr + +c#n - 1, k + 1' - c#n - 1, k - 1'/ s 2 + +Cr^2/ + +c#n - 1, k + 1' - 2 + c#n - 1, k' + c#n - 1, k - 1'/ s 2';
c#0, k_' := N#c0 s. x - k + Ax';
ListPlot#Table#Table#Ax + j, c#n, j', j, dominio##1'' s Ax, dominio##2'' s Ax', n, 0, subdivisoest, 30', Joined - True, PlotRange - Full,
AxesLabel - "x", "Concentrao", PlotLabel - "Evoluo Temporal com Nmero de Courant Igual a " <> ToString#N#Cr'', PlotLegend -
"t=0s", "t=3s", "t=6s", "t=9s", "t=12s", LegendPosition - 0.5, 0.2, LegendSize - .5, .25, Filling - Axis, PlotMarkers - Automatic''
54 ApresentaoSENC.nb
Resolvendo a Equao de Adveco o
t
c +vo
x
c =0
MDFAdvecoExplcito#Piecewise#0, 0 s x s 1, 5, 1 < x s 2, 0, x > 2', -2, 20, 120, 165, 1, 12, 2'
MDFAdvecoExplcito#Piecewise#0, 0 s x s 1, 5, 1 < x s 2, 0, 2 < x s 3, 10, 3 < x s 4, 0, 4 < x', -2, 20, 120, 165, 1, 12, 2'
ApresentaoSENC.nb 55
Resolvendo a Equao de Difuso o
t
c -Do
x x
c =0
Para resolver a equao de difuso, pode-se utilizar um esquema de diferenas finitas com avano no tempo e centrado no espao
MDFDifusoExplcito#c0x_, ct0_, dominio_, subdivisoest_, subdivisoesx_, D_, passostempo_' :=
Module#At = passostempo s subdivisoest, Ax = +dominio##2'' - dominio##1''/ s subdivisoesx, Neu,
Clear#c';
Neu = D + At s +Ax^2/;
c#n_, k_' := c#n, k' = c#n - 1, k' + Neu + +c#n - 1, k + 1' - 2 + c#n - 1, k' + c#n - 1, k - 1'/;
c#0, k_' := c0x s. x - k + Ax;
c#n_, 0' := ct0 s. t - n + At;
ListPlot#Table#Table#Ax + j, c#n, j', j, dominio##1'' s Ax, dominio##2'' s Ax', n, 0, subdivisoest, 30', Joined - True, PlotRange - Full,
AxesLabel - "x", "Concentrao", PlotLabel - "Evoluo Temporal com Nmero de Neumann " <> ToString#N#Neu'', PlotLegend -
"t=0s", "t=3s", "t=6s", "t=9s", "t=12s", LegendPosition - 0.5, 0.2, LegendSize - .5, .25, Filling - Axis, PlotMarkers - Automatic''
56 ApresentaoSENC.nb
Resolvendo a Equao de Difuso o
t
c -Do
x x
c =0
Table%MDFDifusoExplcito%
0 0 s x < 1
6 + N#Sin#+x - 1/ + Pi'' 1 s x < 2
0 2 s x < 3
12 + N#Sin#+x - 1/ + Pi'' 3 s x s 4
0 x > 4
, 0 + t, 0, 6, 120, 100, 18 + i s 1000, 12), i, 0.25, 0.5, 1)
ApresentaoSENC.nb 57
Fim...
Muito Obrigado!
58 ApresentaoSENC.nb