Copy of Introduction to Sage

1505 days ago by wns9546

load(os.environ['SAGE_STARTUP_FILE']) 
       

Sage는 대수적 계산을 할수있는 프로그램(Computer Algebra System (CAS))으로 무료로 sagemath.org 에서 다운로드하여 설치 할 수 있다. 웹서버를 인터페이서로 사용하며 브라우저를 통해 접속하여 사용하기 때문에 인터넷이되는 모든 장소에서 이용할 수 있다. 세이지의 기본언어는 객체지향 언어인  파이썬(Python)이며 이를 사용하여 프로그래밍도 할 수 있다. http://sage.kunsan.ac.kr 에 접속하여 계정을 만들고 사용한다.

대수(Algebra)

덧셈

2+3 
       
5
5
2-3 
       

                                
                            

                                
2*3 
       
6
6
1.5/5 
       
0.300000000000000
0.300000000000000
2^3 
       
8
8
2**3 
       
8
8
2^(-3) 
       
1/8
1/8

인수분해

factor(10021567679000000000000797089) 
       
3 * 13 * 443 * 121367 * 4779326644317538771
3 * 13 * 443 * 121367 * 4779326644317538771

전개하기

var('a,b,c') #변수를 처음 도입할때 선언을 한다. a,b,c 는 이제 변수로 사용가능. 주의: #뒤의 모든것은 무시된다. 
       
(a, b, c)
(a, b, c)
(a+b)^2 
       
(a + b)^2
(a + b)^2
var('u,v') #u,v 는 변수가 된다 
       
(u, v)
(u, v)
expand((a+b)^10) 
       
a^10 + 10*a^9*b + 45*a^8*b^2 + 120*a^7*b^3 + 210*a^6*b^4 + 252*a^5*b^5 +
210*a^4*b^6 + 120*a^3*b^7 + 45*a^2*b^8 + 10*a*b^9 + b^10
a^10 + 10*a^9*b + 45*a^8*b^2 + 120*a^7*b^3 + 210*a^6*b^4 + 252*a^5*b^5 + 210*a^4*b^6 + 120*a^3*b^7 + 45*a^2*b^8 + 10*a*b^9 + b^10

방정식 해 구하기

solve(x^2-3*x+1==0,x) #방정식을 나타낼 때 == 을 사용함에 주의. 
       
[x == -1/2*sqrt(5) + 3/2, x == 1/2*sqrt(5) + 3/2]
[x == -1/2*sqrt(5) + 3/2, x == 1/2*sqrt(5) + 3/2]
solve(x^5-3*x^2-x+3==0,x) 
       
[x == -1/2*(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3)*(I*sqrt(3) + 1) +
1/6*(-I*sqrt(3) + 1)/(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3), x ==
-1/2*(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3)*(-I*sqrt(3) + 1) +
1/6*(I*sqrt(3) + 1)/(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3), x ==
(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3) - 1/3/(1/18*sqrt(247)*sqrt(3) +
3/2)^(1/3), x == 1, x == -1]
[x == -1/2*(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3)*(I*sqrt(3) + 1) + 1/6*(-I*sqrt(3) + 1)/(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3), x == -1/2*(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3)*(-I*sqrt(3) + 1) + 1/6*(I*sqrt(3) + 1)/(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3), x == (1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3) - 1/3/(1/18*sqrt(247)*sqrt(3) + 3/2)^(1/3), x == 1, x == -1]
Numerical solution
find_root(sin(x)-cos(x),0,2) 
       

                                
                            

                                

연립방정식

var('x,y,z') #변수 y를 도입하자 
       
(x, y, z)
(x, y, z)
solve([x-y==3,x+y==5],x,y) 
       
[[x == 4, y == 1]]
[[x == 4, y == 1]]
solve([2*x-y+z==2,x+y+z==-3,3*x-y+2*z==0],x,y,z) 
       
[[x == 3, y == -1, z == -5]]
[[x == 3, y == -1, z == -5]]

함수 (Function): 함수정의는 아래 두가지 방법을 사용하여 할 수 있다.

f(x)=x*sin(x) 
       
f(1.) 
       
0.841470984807897
0.841470984807897

다음은 파이썬 방법이다.

함수 k(x)=s*sin(x)를 정의한다

def k(x): return x*sin(x) 
       

함수 $h(x,y)= (x+y)^{10}+2 x y +x^2$

def h(x,y): return x**2+2*x*y+(x+y)**10 
       
def h(x,y): b=x**2+2*x*y+(x+y)**10 return b 
       
h(1,2) 
       
59054
59054
def h1(x,y): return x**2+2*x*y+(x+y)**10 
       
h(1,2) 
       
59054
59054
h1(1,2) 
       
59054
59054
# e^(x+y) def g(x,y): return exp(x+y) 
       
g(1,1) 
       
e^2
e^2
var('y') 
       
y
y

미분(Differentiation)

$\frac{d}{dx} k(x)$

def k(x): return sin(x**2*cos(x)) 
       
diff(k(x),x) 
       
-(x^2*sin(x) - 2*x*cos(x))*cos(x^2*cos(x))
-(x^2*sin(x) - 2*x*cos(x))*cos(x^2*cos(x))

$\frac{d}{dx} f(x)$

diff(f(x),x) 
       
x*cos(x) + sin(x)
x*cos(x) + sin(x)

$\frac{d}{dx} \sin(x)$

diff(sin(x),x) 
       
cos(x)
cos(x)
diff(cos(x),x,97) 
       
-sin(x)
-sin(x)

편미분(Partial Differentiation)

$\frac{\partial}{\partial x} \sin(x y)$

y=var('y') 
       
diff(sin(x*y),x) 
       
y*cos(x*y)
y*cos(x*y)
diff(sin(x*y),x,20) 
       
y^20*sin(x*y)
y^20*sin(x*y)
diff(sin(x*y),x,2,y,3) 
       
x^3*y^2*cos(x*y) + 6*x^2*y*sin(x*y) - 6*x*cos(x*y)
x^3*y^2*cos(x*y) + 6*x^2*y*sin(x*y) - 6*x*cos(x*y)
diff(sin(x*y),y,3,x,2) 
       
x^3*y^2*cos(x*y) + 6*x^2*y*sin(x*y) - 6*x*cos(x*y)
x^3*y^2*cos(x*y) + 6*x^2*y*sin(x*y) - 6*x*cos(x*y)

$\frac{\partial^{10}}{\partial y^{10}} \sin(xy)$

diff(sin(x*y),y,10) 
       
-x^10*sin(x*y)
-x^10*sin(x*y)
 
       
diff(sin(x*y),x,2,y,3)-diff(sin(x*y),y,3,x,2) 
       
0
0

$\frac{\partial^2}{\partial x^2} \sin(x y)$

diff(sin(x*y),x,2) 
       
-y^2*sin(x*y)
-y^2*sin(x*y)

$\frac{\partial^3}{\partial x \partial y^2} \sin(x y)$

diff(sin(x*y),y,2,x) 
       
-x^2*y*cos(x*y) - 2*x*sin(x*y)
-x^2*y*cos(x*y) - 2*x*sin(x*y)
diff(sin(x*y),x,1,y,2) 
       
-x^2*y*cos(x*y) - 2*x*sin(x*y)
-x^2*y*cos(x*y) - 2*x*sin(x*y)
diff(sin(x*y),x,y) 
       
-x*y*sin(x*y) + cos(x*y)
-x*y*sin(x*y) + cos(x*y)
diff(exp(x**2+y**3*sin(x)),x,2,y,5).subs(x=1,y=2).n() 
       
3.80304538819769e10
3.80304538819769e10

$x^2\sin(xy^7)$ 의 $x=2,y=5$에서의 값을 소수로 구하시오

(x^2*sin(x*y^7)).subs(x=2,y=5).n() 
       
-0.998213235373344
-0.998213235373344

 

적분(Integration)

$\int k(x) dx$

k(x) 
       
sin(x^2*cos(x))
sin(x^2*cos(x))
ff=integral(k(x),x) 
       
integral(sin(x),x) 
       
-cos(x)
-cos(x)
integral(sin(x),x,0,1).n() 
       
0.459697694131860
0.459697694131860
diff(ff,x) 
       
sin(x^2*cos(x))
sin(x^2*cos(x))

$\int_1^2 k(x) dx$

integral(k(x),x,1,2) #정적분 
       
integrate(sin(x^2*cos(x)), x, 1, 2)
integrate(sin(x^2*cos(x)), x, 1, 2)
integral(k(x),x,2,1) 
       
-integrate(sin(x^2*cos(x)), x, 1, 2)
-integrate(sin(x^2*cos(x)), x, 1, 2)

위의 결과를 소수로 나타내기 위해서는 함수 $n()$을 점(.)으로 덧붙이면 된다 (객체지향 언어의 특성).

integral(k(x),x,1,2).n() 
       
-0.032996004851711926
-0.032996004851711926

수치 적분(Numerical integration)

$\int_0^\pi \sin(x)^2 dx$ 를 수치계산과 정확한 계산으로 구해보고 비교해 보자. 두 계산 결과가 오차범위내에서 일치함을 주목하라.

numerical_integral(sin(x)^2,0,pi) #수치계산. 앞의 수가 결과를 나타내며 두번째 수는 오차를 나타내며 e-14는 10^(-14)를 의미한다. 
       
(1.570796326794897, 1.7439342490043163e-14)
(1.570796326794897, 1.7439342490043163e-14)
integral(sin(x)^2,x,0,pi) #정확한(exact) 계산. 이경우 적분변수 (x)를 표시함에 주의 하시오. 
       
1/2*pi
1/2*pi
integral(sin(x)^2,x,0,pi).n(digits=20) #결과를 소수로 나타낸다. 
       
1.5707963267948966192
1.5707963267948966192
integral(exp(-x**2),x,-Infinity,Infinity) 
       
sqrt(pi)
sqrt(pi)

$\int_0^\infty e^{-\sqrt{x}} dx$

f=exp(-sqrt(x)) 
       
integral(f,x,0,Infinity) 
       
2
2
numerical_integral(f,0,Infinity) #Infinity는 무한대를 나타내는 기호. 대문자로 시작함에 주의. 
       
(2.000000014718695, 7.871724825303517e-07)
(2.000000014718695, 7.871724825303517e-07)
integral(f,x,0, Infinity) 
       
2
2
numerical_integral(sin(f),0,pi) 
       
(1.0226025498810094, 6.629450086680393e-07)
(1.0226025498810094, 6.629450086680393e-07)
integral(exp(-x**2),x,0,Infinity).n() 
       
0.886226925452758
0.886226925452758
 
       
plot(sin(cos(x)),x,1,pi,figsize=4) 
       
 
       
plot(exp(-x**2),x,0,1,figsize=4) 
       
plot(exp(-x**2),x,-10,10,figsize=4) 
       
numerical_integral(sin(f),0,pi) 
       
(1.0226025498810094, 6.629450086680393e-07)
(1.0226025498810094, 6.629450086680393e-07)
plot(exp(sin(x)),x,0,100,figsize=4) 
       

대입(substitution)

k(x).subs(x=2) 
       
sin(4*cos(2))
sin(4*cos(2))
k(x)=x*sin(x) 
       
1/(1+x**2).subs(x=pi).n() 
       
0.0919996683503752
0.0919996683503752
var('a,b') 
       
(a, b)
(a, b)
g=(a^2+b^2)/a/b 
       
       
(a^2 + b^2)/(a*b)
(a^2 + b^2)/(a*b)
g.subs(a=1,b=2) 
       
5/2
5/2
f2=(a+b)^5/a^2/b^3 
       
f2 
       
(a + b)^5/(a^2*b^3)
(a + b)^5/(a^2*b^3)
f2.subs(a=2,b=3).n() 
       
28.9351851851852
28.9351851851852
y=var('y') 
       
a=x^2+y^3+2*x*y 
       
       
y^3 + x^2 + 2*x*y
y^3 + x^2 + 2*x*y
a.subs(x=2,y=1.5) 
       
13.3750000000000
13.3750000000000
k(2) 
       
2*sin(2)
2*sin(2)
diff(k(x),x).subs(x=2) 
       
2*cos(2) + sin(2)
2*cos(2) + sin(2)
diff(k(x),x).subs(x=2).n() # x=2에서의 k(x)의 기울기 
       
0.0770037537313969
0.0770037537313969

식을 대입하기

f=sin(x)^2+2*sin(x)+exp(-sin(x)) 
       
var('z') 
       

                                
                            

                                
f.subs(sin(x)==z) 
       

                                
                            

                                

Simplification

a=x*(1-x)/x**2 
       
a.simplify_full() 
       

                                
                            

                                
b=(x-1)**3/(x**2-2*x+1) 
       
b.simplify_full() 
       

                                
                            

                                

실수값얻기

pi #원주율 
       
pi
pi
pi.n(digits=100) 
       
3.1415926535897932384626433832795028841971693993751058209749445923078164\
06286208998628034825342117068
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
e.n() 
       
2.71828182845905
2.71828182845905
k(2) 
       
2*sin(2)
2*sin(2)
k(2).n() 
       
1.81859485365136
1.81859485365136
k(2).n(digits=40) #정확도를 지정할 때 
       
1.818594853651363390792039731823489685405
1.818594853651363390792039731823489685405

List (데이터 저장과 처리에 매우 중요)

var('a,b,c,d,e') #변수 선언 
       
(a, b, c, d, e)
(a, b, c, d, e)
L1=[a,b,3] 
       
L1 
       
[a, b, 3]
[a, b, 3]
len(L1) #리스트의 원소 갯수, length 
       
3
3
L1.append(c) #list에 원소를 추가할때 
       
L1 
       
[a, b, 3, c]
[a, b, 3, c]
L1.append(b) 
       
L1.append(b) 
       
L1 
       
[a, b, 3, c, b, b]
[a, b, 3, c, b, b]
L1.remove(b) #원소 b를 제거 
       
L1 
       
[a, 3, c, b, b]
[a, 3, c, b, b]
L1[2] 
       
c
c
L1.remove(d); L1 
       
Traceback (click to the left of this block for traceback)
...
ValueError: list.remove(x): x not in list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_112.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("TDEucmVtb3ZlKGQpOyBMMQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmp3JDNKn/___code___.py", line 2, in <module>
    exec compile(u'L1.remove(d); L1
  File "", line 1, in <module>
    
ValueError: list.remove(x): x not in list
L1[0];L1[1];L1[2]# 리스트의 원소를 뽑아보자.원소를 지칭하는 인덱스는 0에서 시작함을 주의한다. 
       
a
3
c
a
3
c
L1[2] 
       
c
c
l2=[9,-1,2,-3,5,2,7] 
       
l2[0]*l2[6] 
       
63
63
zero=[] 
       
zero 
       
[]
[]
zero.append(3) 
       
zero 
       
[3]
[3]
l2.sort() #l2를 순서대로 정렬 
       
l2.reverse() 
       
l2 
       
[9, 7, 5, 2, 2, -1, -3]
[9, 7, 5, 2, 2, -1, -3]
range(11) #파이썬 내장 정수 리스트 
       
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(20) 
       
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
range(-20,9,5) 
       
[-20, -15, -10, -5, 0, 5]
[-20, -15, -10, -5, 0, 5]
range(11,30,1) 
       
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
range(2,20,3) 
       
[2, 5, 8, 11, 14, 17]
[2, 5, 8, 11, 14, 17]
range(1,50,3) 
       
[1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49]
[1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49]
srange(2,3,0.1) #세이지 내장 리스트의 하나 
       
[2.00000000000000,
 2.10000000000000,
 2.20000000000000,
 2.30000000000000,
 2.40000000000000,
 2.50000000000000,
 2.60000000000000,
 2.70000000000000,
 2.80000000000000,
 2.90000000000000]
[2.00000000000000,
 2.10000000000000,
 2.20000000000000,
 2.30000000000000,
 2.40000000000000,
 2.50000000000000,
 2.60000000000000,
 2.70000000000000,
 2.80000000000000,
 2.90000000000000]
import numpy #numpy 수치계산 패키지를 불러들인다 
       
numpy.arange(2,10,0.1) #0.1 단위로 원소가 증가 함을 주의 
       
array([ 2. ,  2.1,  2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9,  3. ,
        3.1,  3.2,  3.3,  3.4,  3.5,  3.6,  3.7,  3.8,  3.9,  4. ,  4.1,
        4.2,  4.3,  4.4,  4.5,  4.6,  4.7,  4.8,  4.9,  5. ,  5.1,  5.2,
        5.3,  5.4,  5.5,  5.6,  5.7,  5.8,  5.9,  6. ,  6.1,  6.2,  6.3,
        6.4,  6.5,  6.6,  6.7,  6.8,  6.9,  7. ,  7.1,  7.2,  7.3,  7.4,
        7.5,  7.6,  7.7,  7.8,  7.9,  8. ,  8.1,  8.2,  8.3,  8.4,  8.5,
        8.6,  8.7,  8.8,  8.9,  9. ,  9.1,  9.2,  9.3,  9.4,  9.5,  9.6,
        9.7,  9.8,  9.9])
array([ 2. ,  2.1,  2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9,  3. ,
        3.1,  3.2,  3.3,  3.4,  3.5,  3.6,  3.7,  3.8,  3.9,  4. ,  4.1,
        4.2,  4.3,  4.4,  4.5,  4.6,  4.7,  4.8,  4.9,  5. ,  5.1,  5.2,
        5.3,  5.4,  5.5,  5.6,  5.7,  5.8,  5.9,  6. ,  6.1,  6.2,  6.3,
        6.4,  6.5,  6.6,  6.7,  6.8,  6.9,  7. ,  7.1,  7.2,  7.3,  7.4,
        7.5,  7.6,  7.7,  7.8,  7.9,  8. ,  8.1,  8.2,  8.3,  8.4,  8.5,
        8.6,  8.7,  8.8,  8.9,  9. ,  9.1,  9.2,  9.3,  9.4,  9.5,  9.6,
        9.7,  9.8,  9.9])

Tuples: 바꿀 수 없는 리스트

a=(2,3,4) 
       
a[0] 
       

                                
                            

                                
a[1] 
       

                                
                            

                                
a[2] 
       

                                
                            

                                
len(a) 
       

                                
                            

                                

-----------------------------------------------------------

그래프

k(x)=x*sin(x) 
       
plot(k(x),x,0,10,figsize=4)+plot(x*k(x),x,0,10,figsize=4,color='red') 
       
plot(e^sin(x),x,0,10,figsize=4,color='red')+plot(e^cos(x),x,0,10,figsize=4,color='blue') 
       
Traceback (click to the left of this block for traceback)
...
ValueError: Variable 'e' not found
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_135.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("cGxvdChlXnNpbih4KSx4LDAsMTAsZmlnc2l6ZT00LGNvbG9yPSdyZWQnKStwbG90KGVeY29zKHgpLHgsMCwxMCxmaWdzaXplPTQsY29sb3I9J2JsdWUnKQ=="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmp1a1nhd/___code___.py", line 3, in <module>
    exec compile(u"plot(e**sin(x),x,_sage_const_0 ,_sage_const_10 ,figsize=_sage_const_4 ,color='red')+plot(e**cos(x),x,_sage_const_0 ,_sage_const_10 ,figsize=_sage_const_4 ,color='blue')" + '\n', '', 'single')
  File "", line 1, in <module>
    
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/misc/decorators.py", line 567, in wrapper
    return func(*args, **options)
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/plot/plot.py", line 1941, in plot
    G = funcs.plot(*args, **original_opts)
  File "sage/symbolic/expression.pyx", line 12064, in sage.symbolic.expression.Expression.plot (build/cythonized/sage/symbolic/expression.cpp:68173)
  File "sage/symbolic/expression.pyx", line 12105, in sage.symbolic.expression.Expression._plot_fast_callable (build/cythonized/sage/symbolic/expression.cpp:68463)
  File "sage/ext/fast_callable.pyx", line 495, in sage.ext.fast_callable.fast_callable (build/cythonized/sage/ext/fast_callable.c:4871)
  File "sage/symbolic/expression.pyx", line 11942, in sage.symbolic.expression.Expression._fast_callable_ (build/cythonized/sage/symbolic/expression.cpp:67091)
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 1851, in fast_callable
    return FastCallableConverter(ex, etb)()
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 217, in __call__
    return self.arithmetic(ex, operator)
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 1779, in arithmetic
    return reduce(lambda x,y: self.etb.call(operator, x,y), operands)
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 1779, in <lambda>
    return reduce(lambda x,y: self.etb.call(operator, x,y), operands)
  File "sage/ext/fast_callable.pyx", line 779, in sage.ext.fast_callable.ExpressionTreeBuilder.call (build/cythonized/sage/ext/fast_callable.c:7484)
  File "sage/ext/fast_callable.pyx", line 656, in sage.ext.fast_callable.ExpressionTreeBuilder.__call__ (build/cythonized/sage/ext/fast_callable.c:6570)
  File "sage/symbolic/expression.pyx", line 11942, in sage.symbolic.expression.Expression._fast_callable_ (build/cythonized/sage/symbolic/expression.cpp:67091)
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 1851, in fast_callable
    return FastCallableConverter(ex, etb)()
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 211, in __call__
    return self.symbol(ex)
  File "/home/sagerunner/sage-8.4/local/lib/python2.7/site-packages/sage/symbolic/expression_conversions.py", line 1800, in symbol
    return self.etb.var(SR(ex))
  File "sage/ext/fast_callable.pyx", line 728, in sage.ext.fast_callable.ExpressionTreeBuilder.var (build/cythonized/sage/ext/fast_callable.c:7135)
ValueError: Variable 'e' not found
plot(k(x)*sin(10*x),x,0,10,color='green',figsize=5) # x-축 영역 지정 
       

한 그림창에 여러개 그리기

plot(k(x)*sin(10*x),x,0,10)+plot(k(x),x,0,10, color='red')+plot(k(x)*sin(20*x),x,0,10,color='green',figsize=5) #동시에 그릴때는 + 를 사용한다. 
       

여러개 그림창을 동시에 그리기

fig1=plot(k(x)*sin(10*x),x,0,10)+plot(k(x),x,0,10, color='red') fig2=plot(k(x)*sin(20*x),x,0,10,color='green',figsize=5) graphics_array((fig1,fig2)) 
       

히스토그램

h_data=[sin(i) for i in range(100)] #데이타셑을 만들자 histogram(h_data,bins=50,figsize=5) 
       
h_data 
       
[0,
 sin(1),
 sin(2),
 sin(3),
 sin(4),
 sin(5),
 sin(6),
 sin(7),
 sin(8),
 sin(9),
 sin(10),
 sin(11),
 sin(12),
 sin(13),
 sin(14),
 sin(15),
 sin(16),
 sin(17),
 sin(18),
 sin(19),
 sin(20),
 sin(21),
 sin(22),
 sin(23),
 sin(24),
 sin(25),
 sin(26),
 sin(27),
 sin(28),
 sin(29),
 sin(30),
 sin(31),
 sin(32),
 sin(33),
 sin(34),
 sin(35),
 sin(36),
 sin(37),
 sin(38),
 sin(39),
 sin(40),
 sin(41),
 sin(42),
 sin(43),
 sin(44),
 sin(45),
 sin(46),
 sin(47),
 sin(48),
 sin(49),
 sin(50),
 sin(51),
 sin(52),
 sin(53),
 sin(54),
 sin(55),
 sin(56),
 sin(57),
 sin(58),
 sin(59),
 sin(60),
 sin(61),
 sin(62),
 sin(63),
 sin(64),
 sin(65),
 sin(66),
 sin(67),
 sin(68),
 sin(69),
 sin(70),
 sin(71),
 sin(72),
 sin(73),
 sin(74),
 sin(75),
 sin(76),
 sin(77),
 sin(78),
 sin(79),
 sin(80),
 sin(81),
 sin(82),
 sin(83),
 sin(84),
 sin(85),
 sin(86),
 sin(87),
 sin(88),
 sin(89),
 sin(90),
 sin(91),
 sin(92),
 sin(93),
 sin(94),
 sin(95),
 sin(96),
 sin(97),
 sin(98),
 sin(99)]
[0,
 sin(1),
 sin(2),
 sin(3),
 sin(4),
 sin(5),
 sin(6),
 sin(7),
 sin(8),
 sin(9),
 sin(10),
 sin(11),
 sin(12),
 sin(13),
 sin(14),
 sin(15),
 sin(16),
 sin(17),
 sin(18),
 sin(19),
 sin(20),
 sin(21),
 sin(22),
 sin(23),
 sin(24),
 sin(25),
 sin(26),
 sin(27),
 sin(28),
 sin(29),
 sin(30),
 sin(31),
 sin(32),
 sin(33),
 sin(34),
 sin(35),
 sin(36),
 sin(37),
 sin(38),
 sin(39),
 sin(40),
 sin(41),
 sin(42),
 sin(43),
 sin(44),
 sin(45),
 sin(46),
 sin(47),
 sin(48),
 sin(49),
 sin(50),
 sin(51),
 sin(52),
 sin(53),
 sin(54),
 sin(55),
 sin(56),
 sin(57),
 sin(58),
 sin(59),
 sin(60),
 sin(61),
 sin(62),
 sin(63),
 sin(64),
 sin(65),
 sin(66),
 sin(67),
 sin(68),
 sin(69),
 sin(70),
 sin(71),
 sin(72),
 sin(73),
 sin(74),
 sin(75),
 sin(76),
 sin(77),
 sin(78),
 sin(79),
 sin(80),
 sin(81),
 sin(82),
 sin(83),
 sin(84),
 sin(85),
 sin(86),
 sin(87),
 sin(88),
 sin(89),
 sin(90),
 sin(91),
 sin(92),
 sin(93),
 sin(94),
 sin(95),
 sin(96),
 sin(97),
 sin(98),
 sin(99)]
y=var('y') 
       
g=exp(-x^2-2*y^2) 
       
plot3d(g,(x,-5,5),(y,-5,5)) 
       
[i^2 for i in range(10)] 
       
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
l2=[sin(0.3*i) for i in srange(0,21,0.1)] #l2의 원소는 range(21) 안의 모든 원소를 i에 대입하여 얻어진다. 
       
l2 
       
WARNING: Output truncated!  
full_output.txt



[0.000000000000000,
 0.0299955002024957,
 0.0599640064794446,
 0.0898785491980111,
 0.119712207288919,
 0.149438132473599,
 0.179029573425824,
 0.208459899846100,
 0.237702626427135,
 0.266731436688831,
 0.295520206661339,
 0.324043028394868,
 0.352274233275090,
 0.380188415123161,
 0.407760453059570,
 0.434965534111230,
 0.461779175541483,
 0.488177246882908,
 0.514135991653113,
 0.539632048733969,
 0.564642473395035,
 0.589144757942270,
 0.613116851973434,
 0.636537182221968,
 0.659384671971473,
 0.681638760023334,
 0.703279419200410,
 0.724287174370143,
 0.744643119970860,
 0.764328937025505,
 0.783326909627484,
 0.801619940883777,
 0.819191568300998,
 0.836025978600521,
 0.852108021949363,
 0.867423225594017,
 0.881957806884948,
 0.895698685680048,
 0.908633496115884,
 0.920750597736136,
 0.932039085967227,
 0.942488801931698,
 0.952090341590516,
 0.960835064206073,
 0.968715100118265,
 0.975723357826659,
 0.981853530372360,
 0.987100101013850,
 0.991458348191686,
 0.994924349777581,
 0.997494986604054,
 0.999167945271476,
 0.999941720229966,
 0.999815615134291,
 0.998789743470524,
 0.996865028453919,
 0.994043202198076,
 0.990326804156158,
 0.985719178835554,

...

 -0.977530117665095,
 -0.983413187547309,
 -0.988411251939129,
 -0.992519812919962,
 -0.995735173062244,
 -0.998054438758879,
 -0.999475522827284,
 -0.999997146387718,
 -0.999618840014186,
 -0.998340944156888,
 -0.996164608835842,
 -0.993091792605937,
 -0.989125260794372,
 -0.984268583012044,
 -0.978526129941141,
 -0.971903069401823,
 -0.964405361701533,
 -0.956039754271121,
 -0.946813775592612,
 -0.936735728424082,
 -0.925814682327735,
 -0.914060465507910,
 -0.901483655966358,
 -0.888095571982758,
 -0.873908261929026,
 -0.858934493426595,
 -0.843187741856420,
 -0.826682178232039,
 -0.809432656446623,
 -0.791454699905469,
 -0.772764487555990,
 -0.753378839327749,
 -0.733315200995659,
 -0.712591628479964,
 -0.691226771597129,
 -0.669239857276263,
 -0.646650672256185,
 -0.623479545278687,
 -0.599747328794044,
 -0.575475380195218,
 -0.550685542597638,
 -0.525400125181879,
 -0.499641883116902,
 -0.473433997081934,
 -0.446800052405429,
 -0.419764017839857,
 -0.392350223991451,
 -0.364583341424299,
 -0.336488358458502,
 -0.308090558682375,
 -0.279415498198922,
 -0.250488982627071,
 -0.221337043878354,
 -0.191985916729950,
 -0.162462015215149,
 -0.132791908852511,
 -0.103002298735091,
 -0.0731199935012560,
 -0.0431718852087216,
 -0.0131849251335141]
WARNING: Output truncated!  
full_output.txt



[0.000000000000000,
 0.0299955002024957,
 0.0599640064794446,
 0.0898785491980111,
 0.119712207288919,
 0.149438132473599,
 0.179029573425824,
 0.208459899846100,
 0.237702626427135,
 0.266731436688831,
 0.295520206661339,
 0.324043028394868,
 0.352274233275090,
 0.380188415123161,
 0.407760453059570,
 0.434965534111230,
 0.461779175541483,
 0.488177246882908,
 0.514135991653113,
 0.539632048733969,
 0.564642473395035,
 0.589144757942270,
 0.613116851973434,
 0.636537182221968,
 0.659384671971473,
 0.681638760023334,
 0.703279419200410,
 0.724287174370143,
 0.744643119970860,
 0.764328937025505,
 0.783326909627484,
 0.801619940883777,
 0.819191568300998,
 0.836025978600521,
 0.852108021949363,
 0.867423225594017,
 0.881957806884948,
 0.895698685680048,
 0.908633496115884,
 0.920750597736136,
 0.932039085967227,
 0.942488801931698,
 0.952090341590516,
 0.960835064206073,
 0.968715100118265,
 0.975723357826659,
 0.981853530372360,
 0.987100101013850,
 0.991458348191686,
 0.994924349777581,
 0.997494986604054,
 0.999167945271476,
 0.999941720229966,
 0.999815615134291,
 0.998789743470524,
 0.996865028453919,
 0.994043202198076,
 0.990326804156158,
 0.985719178835554,

...

 -0.977530117665095,
 -0.983413187547309,
 -0.988411251939129,
 -0.992519812919962,
 -0.995735173062244,
 -0.998054438758879,
 -0.999475522827284,
 -0.999997146387718,
 -0.999618840014186,
 -0.998340944156888,
 -0.996164608835842,
 -0.993091792605937,
 -0.989125260794372,
 -0.984268583012044,
 -0.978526129941141,
 -0.971903069401823,
 -0.964405361701533,
 -0.956039754271121,
 -0.946813775592612,
 -0.936735728424082,
 -0.925814682327735,
 -0.914060465507910,
 -0.901483655966358,
 -0.888095571982758,
 -0.873908261929026,
 -0.858934493426595,
 -0.843187741856420,
 -0.826682178232039,
 -0.809432656446623,
 -0.791454699905469,
 -0.772764487555990,
 -0.753378839327749,
 -0.733315200995659,
 -0.712591628479964,
 -0.691226771597129,
 -0.669239857276263,
 -0.646650672256185,
 -0.623479545278687,
 -0.599747328794044,
 -0.575475380195218,
 -0.550685542597638,
 -0.525400125181879,
 -0.499641883116902,
 -0.473433997081934,
 -0.446800052405429,
 -0.419764017839857,
 -0.392350223991451,
 -0.364583341424299,
 -0.336488358458502,
 -0.308090558682375,
 -0.279415498198922,
 -0.250488982627071,
 -0.221337043878354,
 -0.191985916729950,
 -0.162462015215149,
 -0.132791908852511,
 -0.103002298735091,
 -0.0731199935012560,
 -0.0431718852087216,
 -0.0131849251335141]
list_plot(l2,figsize=4) #데이터를 그릴때 
       
list_plot(l2,plotjoined=True,figsize=4,color='green') #점들을 연결해 보자. 
       
l5=[(cos(0.1*i),sin(0.1*i)) for i in range(70)] # range(20)안의 모든 원소를 i에 대입하여 리스트를 만든다. 
       
list_plot(l5,figsize=4,aspect_ratio=1) 
       
list_plot(l5,aspect_ratio=1,plotjoined=True ,figsize=4) #x, y축의 비율을 조절하기 위해서는 aspect_ratio를 사용한다. 
       

3D List Plot

#Generate some 3D data a=2.0 w=1.5 data=[] for t in srange(0,15,0.1): data.append((a*cos(w*t),a*sin(w*t),t)) 
       
list_plot(data,plotjoined=True) 
       

Parametric Plot

t=var('t') 
       
parametric_plot((sin(t^2),exp(0.1*t)),(t,0,3),aspect_ratio=1,figsize=5) 
       
parametric_plot3d((cos(t),sin(t),t),(t,0,6*pi)) 
       

-------------------------------------------------------------------------

선형대수 (Linear Algebra)

u=vector([1,2,3]) #List가 벡터함수의 input임을 주의 
       
       

                                
                            

                                
v=vector([-1,3,5]);v 
       

                                
                            

                                
u.dot_product(v) #내적 
       

                                
                            

                                
u.cross_product(v) #외적 
       

                                
                            

                                
v.cross_product(u) #외적의 순서를 바꾸면 부호가 바뀐다. 
       
(-1, 8, -5)
(-1, 8, -5)
M=matrix([[1,2,3],[2,5,6],[-1,0,3]]);M #행렬함수도 리스트를 받아들임을 주의 
       

                                
                            

                                
M*u 
       

                                
                            

                                
u*M 
       
(2, 12, 24)
(2, 12, 24)
A=vector([1,0,2]) 
       
K=matrix([[2,5,6],[1,0,1],[-1,1,2]]);K 
       

                                
                            

                                
K*A 
       

                                
                            

                                
A*K 
       
(0, 7, 10)
(0, 7, 10)
J=M.inverse() ;J #역행렬을 구한다. 
       

                                
                            

                                
J*M 
       

                                
                            

                                
M*J 
       
[1 0 0]
[0 1 0]
[0 0 1]
[1 0 0]
[0 1 0]
[0 0 1]
iM=M.inverse() 
       
M*iM 
       
[1 0 0]
[0 1 0]
[0 0 1]
[1 0 0]
[0 1 0]
[0 0 1]
iM*M 
       
[1 0 0]
[0 1 0]
[0 0 1]
[1 0 0]
[0 1 0]
[0 0 1]
M.det() #determinant 를 구한다. 
       

                                
                            

                                
K.det() 
       
-11
-11
K.inverse() 
       
[  1/11   4/11  -5/11]
[  3/11 -10/11  -4/11]
[ -1/11   7/11   5/11]
[  1/11   4/11  -5/11]
[  3/11 -10/11  -4/11]
[ -1/11   7/11   5/11]
MM=matrix([[1,1,1,1],[2,0,3,1],[1,1,-6,0],[4,0,5,6]]) 
       
MM.inverse() 
       
[-13/58  37/58  13/58  -2/29]
[ 61/58 -13/58  -3/58  -4/29]
[  4/29   2/29  -4/29  -1/29]
[  1/29 -14/29  -1/29   7/29]
[-13/58  37/58  13/58  -2/29]
[ 61/58 -13/58  -3/58  -4/29]
[  4/29   2/29  -4/29  -1/29]
[  1/29 -14/29  -1/29   7/29]
W=vector([5,-5,7,0]) 
       
(MM.inverse())*W 
       
(-159/58, 349/58, -18/29, 68/29)
(-159/58, 349/58, -18/29, 68/29)
S=matrix([[1,2,3],[2,1,4],[3,4,5]]);S #S는 대칭행렬 
       

                                
                            

                                
       
[1 2 3]
[2 1 4]
[3 4 5]
[1 2 3]
[2 1 4]
[3 4 5]
S.det() 
       

                                
                            

                                
ev=S.eigenvalues();ev #S의 고유값. 대칭행렬의 고유값은 실수임을 유의. 
       

                                
                            

                                
ev[0] 
       
-1.486979759027261?
-1.486979759027261?
 
       
K=S.eigenvectors_right();K #고유벡터. 
       
[(-1.486979759027261?, [(1, -7.323700036494775?, 4.053473437987430?)],
1),
 (-0.592545608423468?, [(1, -0.11487917829899307?,
-0.4542624172751605?)], 1),
 (9.07952536745073?, [(1, 1.188579214793769?, 1.900788979287731?)], 1)]
[(-1.486979759027261?, [(1, -7.323700036494775?, 4.053473437987430?)], 1),
 (-0.592545608423468?, [(1, -0.11487917829899307?, -0.4542624172751605?)], 1),
 (9.07952536745073?, [(1, 1.188579214793769?, 1.900788979287731?)], 1)]
K[0][0] 
       
-1.486979759027261?
-1.486979759027261?
u2=K[1][1];u2 #u1은 K의 첫번째 고유값에 대응하는 고유벡터를 추출한다. 
       
[(1, -0.11487917829899307?, -0.4542624172751605?)]
[(1, -0.11487917829899307?, -0.4542624172751605?)]
u2[0] 
       
(1, -0.11487917829899307?, -0.4542624172751605?)
(1, -0.11487917829899307?, -0.4542624172751605?)
S*u2[0]/K[1][0] 
       
(1, -0.11487917829899307?, -0.4542624172751605?)
(1, -0.11487917829899307?, -0.4542624172751605?)
v1=u1[0];v1 #u1은 원소가 하나인 리스트이고 그 원소가 바로 고유 벡터이다. 
       
Traceback (click to the left of this block for traceback)
...
NameError: name 'u1' is not defined
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_194.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("djE9dTFbMF07djEgI3Ux7J2AIOybkOyGjOqwgCDtlZjrgpjsnbgg66as7Iqk7Yq47J206rOgIOq3uCDsm5DshozqsIAg67CU66GcIOqzoOycoCDrsqHthLDsnbTri6Qu"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmp7MznN_/___code___.py", line 3, in <module>
    exec compile(u'v1=u1[_sage_const_0 ];v1 #u1\uc740 \uc6d0\uc18c\uac00 \ud558\ub098\uc778 \ub9ac\uc2a4\ud2b8\uc774\uace0 \uadf8 \uc6d0\uc18c\uac00 \ubc14\ub85c \uace0\uc720 \ubca1\ud130\uc774\ub2e4.
  File "", line 1, in <module>
    
NameError: name 'u1' is not defined
S*v1/ev[0] #이것이 바로 v1임을 주의해 보시오. 
       
Traceback (click to the left of this block for traceback)
...
NameError: name 'v1' is not defined
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_195.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("Uyp2MS9ldlswXSAgI+ydtOqyg+ydtCDrsJTroZwgdjHsnoTsnYQg7KO87J2Y7ZW0IOuztOyLnOyYpC4="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmplHhweJ/___code___.py", line 3, in <module>
    exec compile(u'S*v1/ev[_sage_const_0 ]  #\uc774\uac83\uc774 \ubc14\ub85c v1\uc784\uc744 \uc8fc\uc758\ud574 \ubcf4\uc2dc\uc624.
  File "", line 1, in <module>
    
NameError: name 'v1' is not defined
 
       

*********두번째와째 세번째 고유값에 대해서도 같은 연습을 해보시오.*************

-------------------------------------------------------------------------

프로그래밍

For-loop (반복할때)

s=0 for i in range(1,101): s=s+i print s 
       
5050
5050
p=1 for i in range (1,101): p=p*i print(p).n() 
       
9.33262154439442e157
9.33262154439442e157
log(p,10).n() 
       

                                
                            

                                
10^0.9700 
       

                                
                            

                                
name=['시형','민정','초현'] 
       
for i in name: print(i) 
       
시형
민정
초현
시형
민정
초현
for i in range(3): print name[i] 
       
시형
민정
초현
시형
민정
초현
s=0 for i in range(0,5001,2): s=s+i print s 
       
6252500
6252500
s=0 for i in range(50): s=s+2*i+1 print s 
       
2500
2500
s=0 for i in range(1,100,2): s=s+i print '1에서100사이의 홀수의합=',s 
       
1에서100사이의 홀수의합= 2500
1에서100사이의 홀수의합= 2500
s=1 for i in range(2,11,2): s=s*i print s 
       
3840
3840
p=1 for i in [1,2,3,5]: #list 안의 모든 원소을 차례로 곱한다. p=p*i print p 
       
30
30
 
       
p=1 for k in range (1,11): p=p*k print p 
       
3628800
3628800
p=1 for i in range(1,101,2): p=p*i print p 
       
272539213975072950298071324540091863329079633054580341373432882344310620\
1171875
2725392139750729502980713245400918633290796330545803413734328823443106201171875

동시에 합과 곱을 계산해 보자

s=0 p=1 q=0 for i in range (1,10): #range 가 1에서 시작. 즉, 1,2,3,...9 s=s+i #인덴트가 있는데까지 loop 이 적용됨. p=p*i q=q+i**2 print s,p,q #인덴트가 없으므로 loop 에서 빠져 나옴. print '합=',s,',', '그리고 product=',p #문자는 따옴표속에. 
       
45 362880 285
합= 45 , 그리고 product= 362880
45 362880 285
합= 45 , 그리고 product= 362880

함수를 사용해 보자

def sumprod(x,y): return x+y, x*y def main(): a=2 b=3 u,v=sumprod(a,b) print '합=',u,',','곱=',v main() 
       
합= 5 , 곱= 6
합= 5 , 곱= 6
def sumprod(x,y): return x+y, x*y a=2 b=3 u,v=sumprod(a,b) print '합=',u,',','곱=',v 
       
합= 5 , 곱= 6
합= 5 , 곱= 6
mA=1 mB=3 mC=5 A1=1 A2=2 B1=2 B2=3 C1=-1 C2=5 M=mA+mB+mC CM1=(mA*A1+mB*B1+mC*C1)/M CM2=(mA*A2+mB*B2+mC*C2)/M print(CM1,CM2) 
       
(2/9, 4)
(2/9, 4)
# A program for center of mass calculation mass=[1,3,5] CO=[[1,2],[2,3],[-1,5]] def sumlist(XX): s=0 for i in XX: s=s+i return s M=sumlist(mass) X=[CO[i][0] for i in range(len(CO))] Y=[CO[i][1] for i in range(len(CO))] def listprod(XX,YY): ZZ=[XX[i]*YY[i] for i in range(len(XX))] return ZZ CM1=sumlist(listprod(mass,X))/M CM2=sumlist(listprod(mass,Y))/M print CM1,',',CM2 
       
2/9 , 4
2/9 , 4
# A program for center of mass calculation def sumlist(XX): s=0 for i in XX: s=s+i return s def listprod(XX,YY): ZZ=[XX[i]*YY[i] for i in range(len(XX))] return ZZ mass=[1,3,5,2,7] CO=[[2,3],[1,1],[4,5],[-1,-2],[-2,7]] M=sumlist(mass) X=[CO[i][0] for i in range(len(CO))] Y=[CO[i][1] for i in range(len(CO))] CM1=sumlist(listprod(mass,X))/M CM2=sumlist(listprod(mass,Y))/M print CM1,',',CM2 
       
1/2 , 38/9
1/2 , 38/9

ex) List 의 원소의 갯수를 헤아려 보자

count=0 mm=[1,2,5,6,777,5,2,100] for i in mm: count=count+1 #loop 속에서 인덱스 i 를 쓰지 않아도 됨을 주의 하라. print '원소의 갯는수는',count,'입니다' 
       
원소의 갯는수는 8 입니다
원소의 갯는수는 8 입니다
len(mm) 
       
8
8
#Counting sum of matrix lements M=[[1,2,3],[2,3,4]] s=0 for i in range(2): for j in range(3): s=s+M[i][j] print s 
       
15
15
def sumlist(XX): s=0 for i in XX: s=s+i return s M=[[1,2,3],[2,3,4]] s=0 for i in range(2): s=s+sumlist(M[i]) print s 
       
15
15
count=0 mk=range(1,1000000,7) for i in mk: count=count+1 print count 
       
142857
142857
s=0 for j in range(4,101,4): s=s+j print s 
       
1300
1300
s=0 for i in range(1,101): s=s+2**i print s 
       
2535301200456458802993406410750
2535301200456458802993406410750
s=0 for i in range(56): s=s+i p=2**s print p 
       
385649988307365214172818656964530258065934919671310232217548006250441182\
654688512107053603857175367946151802604942080766057986716607193331995138\
078062523944232834134301060035963325132466829039948295286901982051209215\
575337264735857513821939535921274399650502614768108420715736845058788545\
887066234845739259259035057475454710888677121850041352012892734056144158\
994382765356263460989042410208779740029161680999518854063792955362004134\
93190419727789712076165429067776
38564998830736521417281865696453025806593491967131023221754800625044118265468851210705360385717536794615180260494208076605798671660719333199513807806252394423283413430106003596332513246682903994829528690198205120921557533726473585751382193953592127439965050261476810842071573684505878854588706623484573925925903505747545471088867712185004135201289273405614415899438276535626346098904241020877974002916168099951885406379295536200413493190419727789712076165429067776
#While-loop s=0 i=0 while (s<1000000 or i <1000): i=i+1 s=s+i print i,s-i 
       
1414 998991
1414 998991

ex) 1에서 1000사이의 홀수의 합을 계산해 보자

s=0 for i in range(1,1000,2): #range 는 1에서 시작하여 2만큼 999까지 간다. 즉, 1,3,5,7,....,999 s=s+i print s 
       
250000
250000
s=0 for i in range(1,100,2): s=s+i**3 print s 
       
12497500
12497500
mm=[3,5,2,-1,6,9] s=0 for i in range(5): s=s+mm[i]*mm[i+1] print s 
       
71
71
s=0 for i in range(1,1001): s=s+1/i print s 
       
533629132822947850455910456240429804096524722803842600971013492484562688\
894971017575060979019850356914090887315504680983784421721178850094643023\
443265660225021002784256328520814055449412104425101426727702947747127089\
179639677796104532246924268664688882815820719848971051107968732493191555\
293970175089315645199760857344730141832840117244122806490743077037366831\
700558002936592350885893602352858528081607595747378366554131755081315225\
17/712886527466509305316638415571427292066835886188589304045200199115432\
408758111149947644415191387158691171781701957525651298026406762100925146\
587100430513107268626814320019660997486274593718834370501543445252373974\
529896314567498212823695623282379401106880926231770886197954079124775455\
804932647573782992335275179673524804246363805113703433121478174685087845\
348567802188807537324992199567205693202909939089168748767269795093160352\
0000
53362913282294785045591045624042980409652472280384260097101349248456268889497101757506097901985035691409088731550468098378442172117885009464302344326566022502100278425632852081405544941210442510142672770294774712708917963967779610453224692426866468888281582071984897105110796873249319155529397017508931564519976085734473014183284011724412280649074307703736683170055800293659235088589360235285852808160759574737836655413175508131522517/7128865274665093053166384155714272920668358861885893040452001991154324087581111499476444151913871586911717817019575256512980264067621009251465871004305131072686268143200196609974862745937188343705015434452523739745298963145674982128236956232823794011068809262317708861979540791247754558049326475737829923352751796735248042463638051137034331214781746850878453485678021888075373249921995672056932029099390891687487672697950931603520000
s.n() 
       
7.48547086055035
7.48547086055035

응용: 적분

pi.n() 
       
3.14159265358979
3.14159265358979

뉴턴 적분 : sine 함수

a=0.0 b=3.14159265358979 N=1000 #구간수 h=(b-a)/N f(x)=sin(x) s=0 xi=a for i in range(N): aa=h*f(xi) s=s+aa xi=xi+h print s 
       
1.99999835506569
1.99999835506569
a=-1.0 b=1.0 N=10 #구간수 h=(b-a)/N f(x)=x**2*exp(-x**2) s=0 xi=a for i in range(N): aa=h*f(xi) s=s+aa xi=xi+h print s 
       
0.378937973263812
0.378937973263812
#while ---loop a=0.0 b=3.14159265358979 N=1000 #구간수 h=(b-a)/N f(x)=sin(x) s=0 xi=a while xi <= b: aa=h*f(xi) s=s+aa xi=xi+h print s 
       
1.99999835506569
1.99999835506569
integral(f(x),x,-1,1).n() 
       
0.000000000000000
0.000000000000000
 
       
L=3.141597/2 h=L/10000 area=0 for i in range(10000): area=area+h*sin(h*i) print area 
       
0.999923631223926
0.999923631223926
L=pi.n()/4 h=L/100000 int=0 for i in range(100000): int=int+h*tan(h*i) print int 
       
0.346569663294292
0.346569663294292
integral(tan(x),x,0,pi/4).n() 
       
0.346573590279973
0.346573590279973
s=0 N=100000 up=3.0 low=0.0 h=(up-low)/N x=low while x <=up : aa=h*cos(x**2) s=s+aa x=x+h print s 
       
0.702892224492688
0.702892224492688
y=var('y') 
       
integral(cos(y**2),y,0,3).n() 
       
0.702863557730268
0.702863557730268

If 조건문 (경우를 따질때)

lst=[-1,-2,0,1,-5,3] for i in lst: if i<0: print i, ':a negative number' elif i==0: #같은지 아닌지를 따질때 == 사용 print i, ':a zero' else: print i, ':a positive number' 
       
-1 :a negative number
-2 :a negative number
0 :a zero
1 :a positive number
-5 :a negative number
3 :a positive number
-1 :a negative number
-2 :a negative number
0 :a zero
1 :a positive number
-5 :a negative number
3 :a positive number
lst=[-1,-2,0,1,2,3,-1,7,9,5,6] for i in lst: if i<0: print i, ':a negative number' #elif 나 else 는 선택사항이지 필수가 아니다. 
       
-1 :a negative number
-2 :a negative number
-1 :a negative number
-1 :a negative number
-2 :a negative number
-1 :a negative number
s=0 for i in lst: if i>0: s=s+i print s 
       
33
33
10%3 
       

                                
                            

                                
lst=[-1,-2,0,1,-5,3] s=0 for a in lst: if 1<=a<=5: s=s+a print s 
       
4
4
s=0 for a in lst: if 1<=a: if a<=5: s=s+a print s 
       
4
4
for k in range(1,21): if (k%3==0): print k, '3 의 배수' else: print k, '3 의 배수 아님' 
       
1 3  의 배수 아님
2 3  의 배수 아님
3 3 의 배수
4 3  의 배수 아님
5 3  의 배수 아님
6 3 의 배수
7 3  의 배수 아님
8 3  의 배수 아님
9 3 의 배수
10 3  의 배수 아님
11 3  의 배수 아님
12 3 의 배수
13 3  의 배수 아님
14 3  의 배수 아님
15 3 의 배수
16 3  의 배수 아님
17 3  의 배수 아님
18 3 의 배수
19 3  의 배수 아님
20 3  의 배수 아님
1 3  의 배수 아님
2 3  의 배수 아님
3 3 의 배수
4 3  의 배수 아님
5 3  의 배수 아님
6 3 의 배수
7 3  의 배수 아님
8 3  의 배수 아님
9 3 의 배수
10 3  의 배수 아님
11 3  의 배수 아님
12 3 의 배수
13 3  의 배수 아님
14 3  의 배수 아님
15 3 의 배수
16 3  의 배수 아님
17 3  의 배수 아님
18 3 의 배수
19 3  의 배수 아님
20 3  의 배수 아님
8%4 
       
0
0
s=0 for i in range(1,256): if i%3==0: s=s+i elif i%5==0: s=s+i print s 
       
15300
15300
s=0 for i in range(1,256): if (i%3==0 or i%5==0): s=s+i print s 
       
15300
15300
s=0 for i in range(1,256): if i%3==0: if i%5==0: s=s+i print s 
       
2295
2295

위 리스트의 음수의 합을 구해보라.

Logical Operators

# AND, OR MM=[-1,2,-3,-5,0,0,2,3,4,7,11,12] for i in MM: if i<0 or i>7: print 1, i for i in MM: if i>0 and i<10: print 2,i 
       
1 -1
1 -3
1 -5
1 11
1 12
2 2
2 2
2 3
2 4
2 7
1 -1
1 -3
1 -5
1 11
1 12
2 2
2 2
2 3
2 4
2 7

While-loop (조건이 맞을때까지 무한 반복)

s=0 j=1 while s<=1000000: s=s+j j=j+1 print j-1, s-j 
       
1414 998990
1414 998990
s=0 i=0 while s<1000: #조건이 만족하는한 반복해서 계산한다. i=i+1 s=s+i print i-1,s-i 
       
44 990
44 990
s=0 for i in range(100): s=s+i if s>=1000: break print i-1,s-i 
       
44 990
44 990
s=0 i=0 while s<=1000: i=i+1 s=s+i print i,s 
       
45 1035
45 1035
s=0 for i in range(45): s=s+i print s 
       
990
990
s1=0 j=0 while s1<10000: j=j+1 s1=s1+j print j-1,s1-i 
       
140 9967
140 9967

For-loop 에서 빠져나오기 (break)

합이 1000을 넘지 않을때까지 더해보자

s=0 for i in range(1000000): s=s+i if s>1000: print i-1,s-i break #loop 에서 빠져나온다. 
       
44 990
44 990
s=0 for i in range(45): s=s+i print s 
       
990
990

Defining a function recursively (순환으로 함수 정의하기)

#factorial 함수를 정의해 해보자. def nfactorial(n): if n==0: return 1 else: return n*nfactorial(n-1) 
       
for i in range(6): print i,nfactorial(i) 
       
0 1
1 1
2 2
3 6
4 24
5 120
0 1
1 1
2 2
3 6
4 24
5 120
#factorial 함수를 while loop 을 사용하여 정의해 보자. def nfacto(n): if n==0: return 1 else: p=n i=n while i>1: i=i-1 p=p*i return p 
       
nfacto(3); nfacto(5) 
       
6
120
6
120
def myabs(n): if n>0: print n else: print -n 
       
myabs(3) 
       
3
3
myabs(-5) 
       
5
5
def facto(n): if n<0: print 'Give a positive number' else: p=1 for i in range(1,n+1): p=p*i return p 
       
facto(4) 
       
24
24
facto(-100) 
       
Give a positive number
Give a positive number
t=0.0 h=0.001 f=2.0 ft=[(t,f)] while t<=2.0: f=f-2*f*h t=t+h ft.append((t,f)) 
       
list_plot(ft,figsize=4,plotjoined=True)+plot(2*exp(-2*x),x,0,2,color='red') 
       
plot(2*exp(-2*x),x,0,2,figsize=4) 
       

행렬곱 계산 프로그램

def matrixmulti(A,B): p=len(A) q=len(A[0]) r=len(B) s=len(B[0]) C=[[0 for i in range(s)] for j in range(p)] #p x s 0-행렬 if q!=r: print('Not multipliable') return else: for i in range(p): for j in range(s): for k in range(q): C[i][j]=C[i][j]+A[i][k]*B[k][j] return C #------------- main program ------------------------------------------- A=[[1,2,3,4],[-1,2,3,5],[-1,-2,0,5]] B=[[2,3],[-1,2],[0,2],[9,1]] C=matrixmulti(A,B) print(C) 
       
[[36, 17], [41, 12], [45, -2]]
[[36, 17], [41, 12], [45, -2]]

Python data types

Integer

2/3 #integer 
       

                                
                            

                                

float---double precision: 소수점이 있는 숫자

2.0/3 
       

                                
                            

                                
float(2)/3 #float 
       

                                
                            

                                
2/float(3) #float 
       

                                
                            

                                
2+3 #integer 
       

                                
                            

                                
2+3.0 #float 
       

                                
                            

                                

Strings--문자열

a='How are you?' print a 
       
How are you?
How are you?
a="How are you?" print a 
       
How are you?
How are you?