matematica_pythonbasico
matematica_pythonbasico
Doherty Andrade
doherty200@[Link]
1
// , divisão inteira
Antes de iniciarmos com exemplos vamos chamar os pacotes que eventualmente vamos pre-
cisar.
In [1]: import numpy as np # biblioteca básica de matemática
import sympy as sp
from sympy import Symbol
import [Link] # SciPy biblioteca de algebra linear
2
2.1 Observação: (PEMDAS) Python resolve expressões matemáticas
Seguindo o padrão PEMDAS: primeiro calcula parênteses, expoentes, multiplicação, divisão e
finalmente, adição e subtração. Vejamos um exemplo
In [13]: 3+4*5
Out[13]: 23
In [14]: (3+4)*5
Out[14]: 35
In [15]: x = 3; y = 4
Out[16]: 12
In [17]: x+10
Out[17]: 13
In [18]: x**2
Out[18]: 9
In [19]: x**y
Out[19]: 81
In [20]: type(5)
Out[20]: int
In [21]: type(5.78)
Out[21]: float
In [22]: z = 3 + 4j
In [23]: type(z)
Out[23]: complex
In [24]: w = complex(5,2)
In [25]: type(w)
3
Out[25]: complex
In [26]: z + w
Out[26]: (8+6j)
In [27]: z*w
Out[27]: (7+26j)
Out[28]: 3.0
Out[29]: 4.0
In [30]: z/w
Out[30]: (0.793103448275862+0.48275862068965514j)
In [31]: [Link]()
Out[31]: (3-4j)
In [32]: abs(z)
Out[32]: 5.0
In [33]: a = input()
In [34]: a
Out[34]: '5'
Comando range:
Quando precisamos que um valor percorra sequencia de valores. Veja exemplo: vamos gerar
os valores de 0 a 9.
In [35]: list(range(10))
Out[35]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [36]: list(range(2,11))
4
In [37]: list(range(0, 42, 3)) #iniciando em zero e pulando de 3 em 3.
Out[37]: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39]
In [38]: n=100
sum([1/i**2 for i in range(1,n+1)])
Out[38]: 1.6349839001848931
Podemos gerar os termos de uma sequência e depois somar. Neste exemplo a sequência é
1 1 1 1
( 0
, 1 , 2 , . . . , n , . . . ).
2 2 2 2
In [39]: mySequence = [1/2**n for n in range(0,100)]
mySum = sum(mySequence)
mySum
Out[39]: 2.0
Definindo funções.
Neste exemplo, definimos a função f ( x ) = x2 .
In [41]: f(10)
Out[41]: 100
In [42]: lambda x: x ** 2
Out[43]: 100
Out[44]: 60
5
Função MAP
A função “map” cuja sintaxe é map(f,s) aplica a função f a todos os elementos de uma sequên-
cia s.
Aqui observe que Python inicia a contagem com 0 e termina com 9. Isso é padrão.
In [48]: a = Rational(2, 5)
a
Out[48]:
2
5
Trabalhando com símbolos, é preciso do pacote sympy.
In [50]: x, y, z = [Link]('x,y,z')
x + 2*y + 3*z - 2*x + 5*y
Out[50]:
− x + 7y + 3z
Resolvendo EDOs e calculando derivadas.
6
Out[51]:
y( x ) = C1 e−5x
Usando o comando odeint: resolve numericamente PVIs.
Como exemplo, tomemos o PVI dado por Resolver o PVI:
dy
= −0.3y( x ) − y( x )
dx
y (0) = 2
# condição inicial
y0 = 2
# intervalo
x = [Link](0,5)
# Resolve o PVI
y1 = odeint(modelo,y0,x)
# plot results
[Link](x,y1,'b-',linewidth=2,label='k=-0.3')
[Link]('tempo')
[Link]('y(x)')
[Link]()
[Link]()
7
In [53]: from sympy import symbols,solve,Eq
x, y, z = symbols('x,y,z')
solve((Eq(3*x+7*y,12*z), Eq(4*x-2*y,5*z)), x, y)
Out[53]:
59z 33z
x: , y:
34 34
8
In [56]: #podemos salvar a figura gerada usando pylab
from pylab import plot, savefig
plot(x,y)
savefig('D:\[Link]')
9
In [57]: #podemos salvar a figura usando matplotlib
from matplotlib import pyplot as plt
plot(x,y)
[Link]('D:\[Link]')
[Link]('D:\[Link]')
10
In [60]: #podemos incluir um gride
x = [Link](-4,4,1000)
y = (x**2)*exp(-sin(x))
[Link](x,y)
grid(True)
[Link]()
#tente outras funções
#y = (x**2)*exp(-x)
11
In [61]: # coordenadas polares
fig = [Link]()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = [Link](0, 2 * [Link], 100)
[Link](t, t, color='blue', lw=3);
## tente (t, cos(t))
## tente (t, sin(t))
## tente (t,exp(-t))
12
In [62]: # coordenadas polares - cardioide
fig = [Link]()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = [Link](0, 2 * [Link], 100)
[Link](t, cos(t), color='blue', lw=3);
13
In [64]: # coordenadas polares- rosa de 3 folhas
fig = [Link]()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = [Link](0, 2 * [Link], 100)
[Link](t, 5*sin(3*t), color='blue', lw=3);
14
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = [Link](0, 5 * [Link], 100)
[Link](t, 5*cos(3*t), color='blue', lw=3);
15
In [67]: # coordenadas polares- rosa de 4 folhas
fig = [Link]()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = [Link](0, 2 * [Link], 100)
[Link](t, 5*cos(4*t), color='blue', lw=3);
16
In [69]: # coordenadas polares- rosa de 8 folhas
fig = [Link]()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = [Link](0, 2 * [Link], 100)
[Link](t, 5*sin(8*t), color='blue', lw=3);
17
x = [Link](-3.14, 3.14, 0.01)
y1 = [Link](x)
y2 = [Link](x)
[Link](figsize =(5 , 5))
[Link](x, y1, label='sin(x)')
[Link](x, y2, label='cos(x)')
[Link]()
[Link]()
[Link]('x')
[Link]('This is the title of the graph')
18
1
2
3
4
0
1
2
3
4
1
3
5
7
9
Out[74]:
2.0
In [76]: fatores(123)
1
3
41
123
19
3.1.2 Fatorial de um número: while
In [77]: #estamos usando o comando input e o comando while
def Fatorial():
"Calcula N! = N(N-1) ... (2)(1) for N >= 1."
n = int(input("Entre com o número inteiro n: "))
fat = 1
i = 1
while i <= n:
fat = fat*i
i = i + 1
In [78]: Fatorial()
In [80]: fatorial(5)
Out[80]:
120
Podemos usar o fatorial para aproximar o valor de e usando a série de Taylor de e x :
∞
xk
ex = ∑ k!
.
k =0
Out[81]:
2.718281828459045
20
0
1
3
7
15
soma = 0
numero = 1
while numero <= n:
soma = soma + numero
numero = numero + 1
return soma
In [84]: Soma(4)
Out[84]:
10
In [85]: Soma(100)
Out[85]:
5050
Pequena mudança na soma
In [87]: soma2(5)
Out[87]:
55
21
5 Sequência de Fibonacci
Asequência de Fibonacci é a sequência 0, 1,1, 2, 3, 5, 8 , 13,. . . , onde o um termo é soma dos dois
imediatamente anteriores. Isto é,
a n = a n −1 + a n −2 .
[0, 1, 1]
[0, 1, 1, 2]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13, 21]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946
22
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13, 21]
In [90]: #usando if
# par ou impar
def parouimpar():
n = int(input("Digite um número natural: "))
if n % 2 == 0: # se n é múltiplo de 2
print(n, "é par")
if n % 2 != 0: # se n não é múltiplo de 2
print(n , "é impar")
In [91]: parouimpar()
if n % 7 == 0: # se n é múltiplo de 7
print(n, "é múltiplo de 7")
if n % 7 != 0: # se n não é múltiplo de 7
print(n , " não é múltiplo de 7")
print("fim.")
#-----
if __name__ == '__main__':
mult7()
6 Fórmula de Ramanujan
A fórmula de Ramanujan para π é uma série numérica maravilhosa para expressar π que converge
muito rapidamente:
23
√
1 2 2 ∞ (4k)! 1103 + 26390k
992 k∑
=
π =0
k!4 3964k
Para encontrar uma aproximação para π usamos um número finito de termos, a seguir usando
os três primeiros termos da série para obter uma boa aproximação para π:
992 1
π≈ √
2 2 1103 + 4! 1103+26390 8! 1103+26390(2)
3964
+ 24 3968
Out[93]:
3.141592653589793
In [94]: #Melhorando um pouco mais-- calculando com qualquer soma parcial tomando n qualquer
import numpy as np
import math
n = 10
(99**2)/(2*[Link](2))*(1/(sum([[Link](4*k)*(1103+26390*k)/
([Link](k)**4*396**(4*k)) for k in range(0,n+1)]))
Out[94]:
3.141592653589793
In [96]: ramanujan(20)
Out[96]:
3.141592653589793
7 If - else
If-else: Um if-else é utilizado quando temos apenas duas alternativas. Quando o número de al-
ternativas é maior, podemos aninhar comandos if-else. Por exemplo, considere o problema de
ler a nota de um aluno para verificar se ele está reprovado, está de recuperação ou foi aprovado.
Suponha que as notas são números inteiros entre 0 e 100. Um aluno está reprovado se sua nota e
menor que 30, está de recuperação se sua nota é um inteiro entre 30 e 49 e está aprovado se sua
nota é pelo menos 50. Uma solução aninhando comandos if-else seria:
24
In [97]: def main():
nota = int(input("Digite uma nota inteira entre 0 e 100: "))
print("fim.")
#-----
if __name__ == '__main__':
main()
elif:
elif é apenas uma contração do else if que torna mais claro o tratamento das várias alternativas,
encadeando as condições. Blocos de elif podem ser repetido várias vezes.
print("fim.")
#-----
if __name__ == '__main__':
main()
25
7.0.1 Testando numeros primos
In [99]: import math
def ehprimo(n):
for d in range(2,int([Link](n)+1)):
if n%d == 0:
return False
return True
In [100]: ehprimo(6173)
Out[100]: True
8 Primos de Mersenne
São números primos da forma M p = 2 p − 1, onde p é primo. Mesmo que p seja primo, M p pode
não ser primo, é o caso de p = 11.
O conhecimento de números primos grandes é a base da segurança da criptografia.
In [102]: mersene(11)
2047
In [104]: merseneprimo(11)
26
if ehprimo(2**n-1):
print(n, 'e,', 2**n-1,',o numero e o Mersene sao primos')
else:
print(2**n-1,',o numero de Mersene NÃO é primo')
else:
print(n,', NÃO é primo')
In [106]: merseneprimo2(5)
In [108]: merseneprimo3(20)
27
Criando uma função que recebe Fahrenheit e devolve Celsius
In [110]: Celsius(98.6)
m = p*0.0254
print(m, ' metros')
#-----
if __name__ == '__main__':
metro( )
9 Conjectura de Collatz
Seja a um inteiro positivo e a sequência definida recursivamente do seguinte modo: se a é par tome
a sua metade, e se a é impar tome 3a + 1. Repita o processo até atingir o número 1. A conjecura de
Collatz afirma que esta sequencia sempre atingirá 1.
28
In [113]: collatz(67)
Out[113]:
[67, 202, 101, 304, 152, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40,
Razão Áurea
def aurea(x,y):
a = x/y
b = (x+y)/x
if a == b:
print('há razao aurea')
else:
print('não ha razao aurea')
In [115]: aurea(1,2)
In [116]: f = 1.618033988749895
aurea(3*f,3)
há razao aurea
def bask(a,b,c):
if (b**2-4*a*c) >= 0:
x1 = (-b+[Link](b**2-4*a*c))/(2*a)
x2 = (-[Link](b**2-4*a*c))/(2*a)
print('as raizes reais sao:,',x1,x2)
else:
print('as raizes sao complexas')
x2 − x − 1 = 0.
In [118]: bask(1,-1,-1)
29
In [119]: #geral
from cmath import sqrt
import numpy as np
def bask2(a,b,c):
if (b**2-4*a*c) >= 0:
x1 = (-b+[Link](b**2-4*a*c))/(2*a)
x2 = (-[Link](b**2-4*a*c))/(2*a)
print('as raizes reais sao:,',x1,'e', x2)
else:
x1 = (-b+ sqrt(b**2-4*a*c))/(2*a)
x2 = (-b- sqrt(b**2-4*a*c))/(2*a)
print('as raizes sao complexas:,', x1,'e', x2)
In [120]: bask2(1,3,9)
10 Um pouco de estatística
In [121]: lista = [1,2,3,4,5,6]
Out[122]: 21
Out[123]:
Out[124]:
3.5
30
11 Álgebra e Matemática Simbólica com Sympy
In [126]: from sympy import Symbol
x = Symbol('x')
In [127]: x + x + 1
Out[127]:
2x + 1
In [128]: x= Symbol('x')
y = Symbol('y')
z = Symbol('z')
In [129]: s = x*y+x*y
s
Out[129]:
2xy
31
Out[130]:
( x + 2) ( y + 3)
Out[131]:
( x − y) ( x + y)
Exemplo: fatorar a expressão
x3 + 3x2 y + 3xy2 + y3 .
Out[134]:
x−1
Out[135]:
x2 + 2x + 1
3 2 2 3
x + 3·x ·y + 3·x·y + y
In [137]: expr3 = x*x + x*y + x*y + y*y ## substituindo valores nas expressores
res = [Link]({x:1, y:2})
In [138]: res
Out[138]:
In [139]: [Link]({x:1-y})
Out[139]:
32
11.0.1 Resolvendo equações
In [140]: from sympy import Symbol, solve
x = Symbol('x')
expr = x - 5 - 7
solve(expr)
Out[140]:
[12]
Out[141]:
[{ x : −4} , { x : −1}]
In [142]: x=Symbol('x')
expr = x**2 + x + 1
solve(expr, dict=True)
Out[142]:
"( √ ) ( √ )#
1 3i 1 3i
x:− − , x:− +
2 2 2 2
In [143]: x = Symbol('x')
y = Symbol('y')
expr1 = 2*x + 3*y - 6
expr2 = 3*x + 2*y - 12
Out[144]:
24 6
x: , y:−
5 5
11.0.2 Derivada
In [145]: from sympy import *
x, y, z = symbols('x y z')
In [146]: diff(cos(x), x)
Out[146]:
− sin ( x )
33
In [147]: diff(x**4, x, x, x)
Out[147]:
24x
Out[148]:
11.0.3 Integral
In [149]: integrate(cos(x), x)
Out[149]:
sin ( x )
Out[150]:
Out[151]:
Out[152]:
11.0.5 Limites
In [153]: limit(sin(x)/x, x, 0)
Out[153]:
34
Out[154]:
Out[155]:
Out[156]:
{−3, 3}
Out[157]:
1
2,
2
In [158]: from sympy import symbols,solve,Eq
x, y, z = symbols('x,y,z')
solve((Eq(3*x+7*y,12*z), Eq(4*x-2*y,5*z)), x, y)
Out[158]:
59z 33z
x: , y:
34 34
In [159]: import sympy # chama o sympy
x, y, z = [Link]('x, y, z') # cria os simbolos
eq = x - x ** 3 # define a equaçao
[Link](eq, x) # resolsolve a eq = 0
Out[159]:
[−1, 0, 1]
11.0.6 Matrizes
In [160]: from sympy import *
init_printing(use_unicode=True)
Out[161]:
1 −1
3 4
0 2
35
In [162]: Matrix([1, 2, 3])
Out[162]:
1
2
3
Out[163]:
1 2 3
−2 0 4
In [164]: [Link]
Out[164]:
(2, 3)
Out[165]:
1 5 8
−2 7 1
In [167]: M * N
Out[167]:
3 22
12 39
In [168]: 2*M
Out[168]:
2 6
8 10
In [169]: M**2,
## tente tb M*M
36
Out[169]:
13 18
24 37
Out[170]:
1 4
3 5
In [171]: [Link]()
Out[171]:
−7
Out[172]:
1 0 1 3
2 3 4 7
−1 −3 −3 −4
In [173]: [Link]()
Out[173]:
1 0 1 3
0 1 2 1 , (0, 1)
3 3
0 0 0 0
Autovalores e autovetores:
In [174]: M = Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])
[Link]() # retorna autovalores com multiplicidade algébrica
Out[174]:
{−2 : 1, 3 : 1, 5 : 2}
37
Out[175]:
11.0.8 Diagonalização
Para diagonalizar uma matriza, use o comando diagonalize. Sympy retorna um par (P,D), onde D
diagonal e M = PDP−1 .
In [176]: P, D = [Link]()
In [177]: P
Out[177]:
0 1 1 0
1
1 1 −1
1 1 1 0
1 1 0 1
In [178]: D
Out[178]:
−2 0 0 0
0 3 0 0
0 0 5 0
0 0 0 5
Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])
In [181]: p
Out[181]:
PurePoly λ4 − 11λ3 + 29λ2 + 35λ − 150, λ, domain = Z
In [182]: factor(p)
38
Out[182]:
( λ − 5)2 ( λ − 3) ( λ + 2)
Out[183]:
1 2 4 2
3 15 − 15 15
5 1 29
− 30 2
6 3 15
5 2
− 23 2
6 15 30 15
5 2
6 15 − 29
30
1
3
12 Decomposição LU
In [184]: #Decomposição LU
import scipy
import [Link] # SciPy Linear Algebra Library
A = [Link]([ [7, 3, -1, 2], [3, 10, 1, -4], [-1, 1, 8, -1], [2, -4, -1, 9] ])
P, L, U = [Link](A)
print('A=',A)
print('P=',P)
print('L=',L)
print('U=',U)
A= [[ 7 3 -1 2]
[ 3 10 1 -4]
[-1 1 8 -1]
[ 2 -4 -1 9]]
P= [[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
L= [[ 1. 0. 0. 0. ]
[ 0.42857143 1. 0. 0. ]
[-0.14285714 0.16393443 1. 0. ]
[ 0.28571429 -0.55737705 0.01075269 1. ]]
U= [[ 7. 3. -1. 2. ]
[ 0. 8.71428571 1.42857143 -4.85714286]
[ 0. 0. 7.62295082 0.08196721]
[ 0. 0. 0. 5.72043011]]
39
13 Decomposição Cholesky
In [185]: #Decomposição Cholesky
import pprint
import scipy
import [Link] # SciPy Linear Algebra Library
A = [Link]([[20, 3, 4, 8], [3, 20, 5, 1], [4, 5, 30, 7], [8, 1, 7, 25]])
L = [Link](A, lower=True)
U = [Link](A, lower=False)
print('A=')
[Link](A)
print('L=')
[Link](L)
print('Lt=U=')
[Link](U)
A=
array([[20, 3, 4, 8],
[ 3, 20, 5, 1],
[ 4, 5, 30, 7],
[ 8, 1, 7, 25]])
L=
array([[ 4.47213595, 0. , 0. , 0. ],
[ 0.67082039, 4.42153819, 0. , 0. ],
[ 0.89442719, 0.9951288 , 5.31128221, 0. ],
[ 1.78885438, -0.04523313, 1.02517859, 4.5548834 ]])
Lt=U=
array([[ 4.47213595, 0.67082039, 0.89442719, 1.78885438],
[ 0. , 4.42153819, 0.9951288 , -0.04523313],
[ 0. , 0. , 5.31128221, 1.02517859],
[ 0. , 0. , 0. , 4.5548834 ]])
14 Otimização
Otimização
Em geral precisamos encontrar o maximo e o minimo de uma função particular f escalar. As
rotinas de otimização são tipicamente de minimização. Para maximizar invertemos o sinal de f
definindo uma nova função g(x)=−f (x) e minimizamos g.
A seguir apresentamos um exemplo de como utilizar a rotina de otimização para minimizar
f (x)=cos(x)−3exp(−(x−0.2)2).
Chamamos o pacote de otimização digitando [Link] que precisa de dois argu-
mentos, o valor x0 a partir do qual iniciamos a busca para o mínimo.
40
In [186]: from scipy import arange, cos, exp
from [Link] import fmin
import pylab
def f(x):
return cos(x) - 3 * exp( -(x - 0.2) ** 2)
# plota função
x = arange(-10, 10, 0.1)
y = f(x)
[Link](x, y, label='$\cos(x)-3e^{-(x-0.2)^2}$')
[Link]('x')
[Link]()
[Link]([-5, 5, -2.2, 0.5])
[Link](loc='lower left')
Optimization terminated successfully.
Current function value: -2.023866
Iterations: 16
Function evaluations: 32
Inicia a pesquisa com x=1., minimo é [0.23964844]
Optimization terminated successfully.
Current function value: -1.000529
Iterations: 16
Function evaluations: 32
Inicia a pesquisa com x=2., minimo é [3.13847656]
41
In [187]: from scipy import arange, cos, exp
from [Link] import fmin
import pylab
def f(x):
return x**4-x**2+4*x
# plota função
x = arange(-3, 3, 0.1)
y = f(x)
[Link](x, y, label='$teste$')
[Link]('x')
[Link]()
[Link]([-3, 3, -5, 0.5])
42
Function evaluations: 24
Inicia a pesquisa com x=-1., minimo é [-1.16533203]
Optimization terminated successfully.
Current function value: -4.175166
Iterations: 19
Function evaluations: 38
Inicia a pesquisa com x=1., minimo é [-1.16533203]
Out[187]:
1.1102230246251565e-16
43
15 Aprendendo a Programar: exemplos
15.0.1 Exemplo 1: usando o comando for
In [189]: for i in range(10):
print(2**i - 1)
0
1
3
7
15
31
63
127
255
511
1.1102230246251565e-16
16 Função anônima
Python tem uma infinidade de funções matemáticas já definidas tais como ceil, floor, fabs, facto-
rial, log, exp, sin, cos, etc. Mas as vezes precisamos de outras.
Vejamos como definir uma função matemática.
As funções anônimas — em Python também chamadas de expressões lambda — representam
um recurso bem interessante da linguagem Python, mas cuja utilidade pode não ser muito óbvia
à primeira vista.
Uma função anônima é útil principalmente nos casos em que precisamos de uma função para
ser passada como parâmetro para outra função, e que não será mais necessária após isso, como se
fosse “descartável”.
Vamos definir uma função de dois modos diferentes: usando o def e usando lambda.
In [192]: func1(2)
Out[192]:
44
In [193]: func2 = lambda x: x**2
In [194]: func2(5)
Out[194]:
25
In [195]: func2([Link])
Out[195]:
9.869604401089358
In [ ]:
# Cria vetores X e Y
x = [Link](range(-10,10))
y = x ** 3
# Cria o plot
[Link](x,y)
# Mostra o plot
[Link]()
45
In [199]: # Importa módulos que serão necessários
import [Link] as plt
import numpy as np
# Cria vetores X e Y
x = [Link](range(-10,10))
y = x ** 3
# Cria o plot
[Link](x,y)
# Mostra o plor
[Link]()
46
17 Função Zeta de Riemann
A função Zeta de Riemann é definida pela soma infinita (série):
∞
1
ζ (s) = ∑ ns
.
n =1
1.5497677311665408
Alguns valores especiais da função Zeta de Riemann:
π2 π4
ζ (2) = and ζ (4) =
6 90
Vamos usar a função zeta acima para calcular uma aproximação de ζ (2), com s = 2 e N = 100000:
47
In [202]: zeta(2,100000)
Out[202]:
1.644924066898227
In [203]: zeta(4,100000)
Out[203]:
1.0823232337111381
a+b+c
s= .
2
A área do triangulo pela fórmula de Heron é:
q
A = s(s − a)(s − b)(s − c).
Vamos criar uma função que calcula a área de um triângulo utilizando a fórmula de Heron
conhecido os vértices do triângulo.
Parametros
----------
vertices : os vertices do triangulo [(x1,y1),(x2,y2),(x3,y3)].
Retorna
-------
Area do triângulo pela fórmula de Heron.
Examplo
--------
area_triangulo([(-1,2),(-3,-1),(4,1)])
'''
# calculando distancia do vertice 1 ao vertice2
# calculando (x_1-x_2)
a_x = abs(vertices[0][0] - vertices[1][0])
# calculando (y_1-y_2)
a_y = abs(vertices[0][1] - vertices[1][1])
# calculando distancia do vertice 1 ao vertice2
a = (a_x**2 + a_y**2)**0.5
48
# calculando a distancia entre os vertices 1 e 2
b_x = abs(vertices[1][0] - vertices[2][0])
b_y = abs(vertices[1][1] - vertices[2][1])
b = (b_x**2 + b_y**2)**0.5
# calculando o semiperimentro
s = (a + b + c)/2
# Calculando a área usando a formula de Heron
area = (s*(s - a)*(s - b)*(s - c))**0.5
return area
In [205]: area_triangulo([(0,0),(0,1),(1,0)])
Out[205]:
0.49999999999999983
Vejamos o desenho deste triangulo.
[Link]()
[Link](xs,ys)
[Link]()
49
In [207]: area_triangulo([(-1,2),(-3,-1),(4,1)])
Out[207]:
8.499999999999996
In [208]: area_triangulo([(0,0),(0,2),(1,1)])
Out[208]:
0.9999999999999997
In [ ]:
50