Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50650 views
1
# CoCalc Examples Documentation File
2
# Copyright: CoCalc Authors, 2015
3
# License: Creative Commons: Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
4
---
5
language: python
6
---
7
category: ["Numpy/Scipy", "Intro"]
8
---
9
title: Numpy Basics
10
descr: >
11
[Numpy](http://docs.scipy.org/) is a library for numerical mathematics.
12
13
It is usually imported via `import numpy as np`.
14
code: |
15
import numpy as np
16
print np, np.__version__
17
---
18
title: Vectors and Matrices
19
descr: >
20
NumPy's main purpose is to create n-dimensional tensors for numerical computations in linear algebra.
21
A vector is 1-D, and constructed via `np.array([...])`.
22
A 2-D array is a matrix: `np.arry([[1, 2][2, -1]])`.
23
code: |
24
import numpy as np
25
print(np.array([1, 2, 5, 10]))
26
print(np.array([[1, -1], [-1, 2]]))
27
#---
28
#title: Basic Arithmetic
29
---
30
category: ["Numpy/Scipy", "Optimization"]
31
title: Optimization, 1D, unconstrained
32
descr: Unconstrained one-dimensional optimization with Scipy.
33
code: |
34
from scipy import optimize
35
def f(x):
36
return 3 * (1 - x) + (x - 2)**2
37
res = optimize.minimize_scalar(f)
38
print(res.x)
39
print(f(res.x))
40
---
41
title: Optimization, 1D, constrained
42
descr: Constrained one-dimensional optimization with Scipy.
43
code: |
44
from scipy import optimize
45
def f(x):
46
return 3 * (1 - x) + (x - 2)**2
47
res = optimize.minimize_scalar(f, bounds=(-1, 1), method='bounded')
48
print(res.x)
49
print(f(res.x))
50
---
51
title: Optimization, ND, unconstrained
52
descr: >
53
Minimize the classical Rosenbock function with starting value $(2,2)$.
54
55
Retrive the minimum $\hat{x}$ via `res.x` from the result object.
56
57
More information: [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html)
58
code: |
59
from scipy import optimize
60
def f(x):
61
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
62
res = optimize.minimize(f, [2, 2])
63
print(res)
64
65