Chapter2

コメント

In [1]:
# コメントです 
print(1) # 1を表示
1
In [2]:
'''
コメント1
コメント2
'''
Out[2]:
'\nコメント1\nコメント2\n'

Print文

In [3]:
print('Control')
Control
In [4]:
print('制御' + '工学')
制御工学
In [5]:
print('制御工学' * 5)
制御工学制御工学制御工学制御工学制御工学

エスケープシーケンス

In [6]:
print(' \' \" \\ ') # クォーテションやバックスラッシュの表示
 ' " \ 
In [7]:
print('制御\t 工学 \n' * 5) # タブと改行
制御	 工学 
制御	 工学 
制御	 工学 
制御	 工学 
制御	 工学 

カウント

In [8]:
len('せいぎょこうがく')
Out[8]:
8

数値

In [9]:
12
Out[9]:
12
In [10]:
0b1010
Out[10]:
10
In [11]:
0xA1
Out[11]:
161
In [12]:
10 / 5
Out[12]:
2.0
In [13]:
17 // 5
Out[13]:
3
In [14]:
17 % 5
Out[14]:
2
In [15]:
3 ** 2
Out[15]:
9

変数

In [16]:
x = 1
print(x)
print(type(x))
1
<class 'int'>
In [17]:
y = 1.0
print(y)
print(type(y))
1.0
<class 'float'>
In [18]:
msg = 'Control'
print(msg)
print(type(msg))
Control
<class 'str'>
In [19]:
ok = True
print(ok)
print(type(ok))
True
<class 'bool'>

型変換

In [20]:
z = int(y)
print(z)
print(type(z))
1
<class 'int'>
In [21]:
word = str(x)
print(word)
print(type(word))
1
<class 'str'>

リスト

In [22]:
data1 = [3, 5, 2, 4, 6, 1]
data1
Out[22]:
[3, 5, 2, 4, 6, 1]
In [23]:
data2 = [ [3, 5, 2], [4, 6, 1] ]
data2
Out[23]:
[[3, 5, 2], [4, 6, 1]]
In [24]:
data1[0]
Out[24]:
3

スライス

In [25]:
data1[0:2]
Out[25]:
[3, 5]
In [26]:
data1[2:4]
Out[26]:
[2, 4]

メソッド

In [27]:
data1 = [3, 5, 2, 4, 6, 1]
data1.append(8)
print(data1)
[3, 5, 2, 4, 6, 1, 8]
In [28]:
data1.insert(0, 8)
print(data1)
[8, 3, 5, 2, 4, 6, 1, 8]
In [29]:
del data1[0]
print(data1)
[3, 5, 2, 4, 6, 1, 8]
In [30]:
data1.pop(0)
print(data1)
[5, 2, 4, 6, 1, 8]

浅いコピー深いコピー

In [31]:
x = [ 1, 2, 3]
y = x
y[0] = 10
print(y) # [10, 2, 3]と出力される 
print(x) # xの値も[10, 2, 3]に変更される
[10, 2, 3]
[10, 2, 3]
In [32]:
x = [ 1, 2, 3]
y = x.copy()
y[0] = 10
print(y) # [10, 2, 3]と出力される
print(x) # xの値は変更されずに[1, 2, 3]と出力される
[10, 2, 3]
[1, 2, 3]

タプル

In [33]:
tuple = (1,2,3,4) # tuple = 1,2,3,4 でもよい 
print(tuple)
print(type(tuple))
(1, 2, 3, 4)
<class 'tuple'>
In [34]:
tuple[0] = 5

TypeErrorTraceback (most recent call last)
<ipython-input-34-e1d06dae70bc> in <module>
----> 1 tuple[0] = 5

TypeError: 'tuple' object does not support item assignment
In [36]:
data = [1, 2, 3, 4]
data[0] = 5
data
Out[36]:
[5, 2, 3, 4]

辞書

In [37]:
d = { 'linestyle': '-.', 'color': 'k' }
In [38]:
print(d) 
print(d['linestyle']) 
print(d['color'])
{'linestyle': '-.', 'color': 'k'}
-.
k
In [39]:
x = { 'linestyle':'--', 'label':'plt' } 
d.update(x)
print(d)
{'linestyle': '--', 'color': 'k', 'label': 'plt'}

if文

In [40]:
x = 1

if x < 0:
    print('x is negative')
elif x == 0:
    print('x is zero')
else:
    print('x is positive')
x is positive
In [41]:
x ,y = -1, -1

if x < 0 and y < 0:
    print('x and y are negative')
x and y are negative
In [42]:
x, y = 1, -1

if x < 0 or y < 0:
    print('x or y is negative')
x or y is negative
In [43]:
x = 2
y = [1, 2, 3] 

if x in y:
    print('x is in y')
x is in y
In [44]:
x = 0
y = [1, 2, 3] 

if x not in y:
    print('x is not in y')
x is not in y

for文

In [45]:
for x in [0, 1, 2]: 
    print(x)
0
1
2
In [46]:
for x in range(0, 3): 
    print(x)
0
1
2
In [47]:
for i, word in enumerate(['a', 'b', 'c']): 
    print(i, word)
0 a
1 b
2 c

練習問題

In [48]:
# プログラム1
for x in range(3):
    print(x) 
    print('python')
0
python
1
python
2
python
In [49]:
# プログラム2
for x in range(3):
    print(x) 
print('python')
0
1
2
python

関数定義

In [50]:
def say_hello(): 
    print('こんにちは')
In [51]:
say_hello()
こんにちは
In [52]:
def subject(name): 
    print(name + '工学')
In [53]:
subject('制御')
制御工学
In [54]:
def add(a, b): 
    c = a + b
    return c
In [55]:
result = add(3, 5)
print(result)
8
In [56]:
def add(*args):
    return args[0] + args[1]
In [57]:
value = [3, 5]
result = add(*value)
print(result)
8

クロージャ

In [58]:
def outer(a, b): 
    def inner(c):
        return c * (a + b) 
    return inner
In [59]:
f = outer(1, 2) 
r = f(3) 
print(r)
9
In [60]:
f2 = outer(3, 4)
r2 = f2(3)
print(r2)
21

ラムダ式(無名関数)

In [61]:
c = (lambda a, b: 2*a + 3*b)(1.0, 4.0) 
print(c)
14.0
In [62]:
data1 = [1, 2, 3, 4, 5]
data2 = [10, 9, 8, 7, 6]
result = list(map(lambda a, b:2*a + 3*b, data1, data2)) 
print(result)
[32, 31, 30, 29, 28]

ジェネレータ

In [63]:
def linestyle_generator():
    linestyle = ['-', '--', '-.', ':'] 
    lineID = 0
    while True:
        yield linestyle[lineID]
        lineID = (lineID + 1) % len(linestyle)
In [64]:
LS = linestyle_generator()
for i in range(5):
    print(next(LS)) # LSの中の yield 部分を1回ずつ実行
-
--
-.
:
-

リスト内包表記

In [65]:
t = (1, 2, 3, 4, 5) 
r1 = [i for i in t] 
print(r1)
[1, 2, 3, 4, 5]
In [66]:
r2 = [i for i in t if i % 2 == 0] 
print(r2)
[2, 4]

練習問題

In [67]:
from numpy import sqrt

# for文を使って足し合わせる 

s=0
for x in range(1,51):
    s += x
print(sqrt(s))

# sumを使う
s = sum(range(1,51)) 
print(sqrt(s))

# generator式を使う
s = sum(x for x in range(1,51)) 
print(sqrt(s))
35.70714214271425
35.70714214271425
35.70714214271425

モジュール

In [68]:
import numpy
In [69]:
import numpy as np
In [70]:
from numpy import sqrt
In [71]:
from numpy.linalg import *
In [72]:
import math
In [73]:
math.sin(0.5)
Out[73]:
0.479425538604203
In [74]:
math.log10(2)
Out[74]:
0.3010299956639812
In [75]:
math.log(2)
Out[75]:
0.6931471805599453
In [76]:
math.pi
Out[76]:
3.141592653589793
In [77]:
math.e
Out[77]:
2.718281828459045

Numpy

In [78]:
import numpy as np
In [79]:
A = np.array([ [1, 2], [-3, 4]])
print(A)
[[ 1  2]
 [-3  4]]
In [80]:
print(A.T)
[[ 1 -3]
 [ 2  4]]
In [81]:
B = np.abs(A)
print(B)
[[1 2]
 [3 4]]
In [82]:
np.linalg.det(A)
Out[82]:
10.000000000000002
In [83]:
np.linalg.matrix_rank(A)
Out[83]:
2
In [84]:
x = np.array([1, 2])
print(x)
[1 2]
In [85]:
np.linalg.norm(x)
Out[85]:
2.23606797749979
In [86]:
w, v = np.linalg.eig(A)
print('eigenvalue=',w)
print('eigenvector=\n',v)
eigenvalue= [2.5+1.93649167j 2.5-1.93649167j]
eigenvector=
 [[0.38729833-0.5j 0.38729833+0.5j]
 [0.77459667+0.j  0.77459667-0.j ]]
In [87]:
C = np.linalg.inv(A)
print(C)
[[ 0.4 -0.2]
 [ 0.3  0.1]]
In [88]:
T = np.arange(0, 10, 1)
print(T)
[0 1 2 3 4 5 6 7 8 9]

Matplotlib

In [89]:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 4 * np.pi, 0.1)
y = np.sin(x)
plt.plot(x, y, c='k')
plt.xlabel('x')
plt.ylabel('y')
plt.grid()

# plt.savefig("matplot_plotexp.pdf", transparent=True, bbox_inches="tight", pad_inches=0.0)
In [90]:
fig, ax = plt.subplots(figsize=(3, 2.3))
ax.plot(x, y, c='k')
ax.set_xlabel('x')
ax.set_ylabel('y')

ax.set_xticks(np.linspace(0, 12, 7))
ax.set_yticks(np.linspace(-1, 1, 9))

ax.grid()

#fig.savefig("matplot_plotexp.pdf", transparent=True, bbox_inches="tight", pad_inches=0.0)
In [91]:
# fig, ax = plt.subplots(2,1)
fig, ax = plt.subplots(2,1, figsize=(6, 4))

x = np.arange(0, 4 * np.pi, 0.1)
y = np.sin(x)
z = np.cos(x)
w = y + z

ax[0].plot(x, y, ls='-', label='sin', c='k')
ax[0].plot(x, z, ls='-.', label='cos', c='k')
ax[0].set_xlabel('x')
ax[0].set_ylabel('y, z')
ax[0].set_xlim(0, 4*np.pi)
ax[0].grid()
ax[0].legend()

ax[1].plot(x, w, color='k', marker='.')
ax[1].set_xlabel('x')
ax[1].set_ylabel('w')
ax[1].set_xlim(0, 4*np.pi)
ax[1].grid(ls=':')

fig.tight_layout()
# fig.savefig("matplot_plotexp2.pdf", transparent=True, bbox_inches="tight", pad_inches=0.0)
In [92]:
import matplotlib.pyplot as plt
import numpy as np
 
x  = np.arange(1, 13)
y1 = np.repeat(2, 12)
y2 = np.repeat(1, 12)
 
markers1 = [".", ",", "o", "v", "^", "<", ">", "1", "2", "3", "4", "8"]
markers2 = ["s", "p", "*", "h", "H", "+", "x", "D", "d", "|", "_", "$x$"]

fig, ax = plt.subplots(1,1, figsize=(6, 1))
for i in x-1:
    ax.scatter(x[i], y1[i], color='k', s=100, marker=markers1[i])
    ax.scatter(x[i], y2[i], color='k', s=100, marker=markers2[i])
    ax.set_xticks(np.linspace(1, 12, 12))
    ax.set_yticks([1,2])
    
# fig.savefig("markers.pdf", transparent=True, bbox_inches="tight", pad_inches=0.0)

Scipy

In [93]:
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def system(y, t):
    if t < 10.0:
        u = 0.0
    else:
        u = 1.0
    
    dydt = (-y + u)/5.0 
    return dydt

y0 = 0.5
t = np.arange(0, 40, 0.04)

y = odeint(system, y0, t)

fig, ax = plt.subplots(figsize=(3, 2.3))
ax.plot(t, y, label='y', c='k')
ax.plot(t, 1 * (t>=10), ls='--', label='u', c='k')
ax.set_xlabel('t')
ax.set_ylabel('y, u')
ax.legend(loc='best')
ax.grid(ls=':')

# fig.savefig("scipy_demo.pdf", transparent=True, bbox_inches="tight", pad_inches=0.0)

Sympy

In [94]:
import sympy as sp 
sp.init_printing()
s = sp.Symbol('s')
root = sp.solve(2 * s**2 +5*s+3, s)
print(root)
[-3/2, -1]
In [95]:
root
Out[95]:
$$\left [ - \frac{3}{2}, \quad -1\right ]$$
In [96]:
f = sp.expand( (s+1)*(s+2)**2, s)
print(f)
s**3 + 5*s**2 + 8*s + 4
In [97]:
f
Out[97]:
$$s^{3} + 5 s^{2} + 8 s + 4$$
In [98]:
g = sp.factor(f, s) 
print(g)
(s + 1)*(s + 2)**2
In [99]:
g
Out[99]:
$$\left(s + 1\right) \left(s + 2\right)^{2}$$