Laboratory Manual for
Calculus and Linear Algebra
with Sage
written by Sang-Gu Lee with Kyung-Won Kim
based on Books of Prof. Sang-Gu Lee (Calculus and Linear Algebra with Sage)
collected and rearranged by Kyung-Won Kim, Shaowei Sun and Sang-Gu Lee
2014. 2. 3
by
Contents
I. Sage Tutorial
1. Introduction
2. How to Use
3. Basic Sage Codes
4. Sage Quick References
5. Related Links for Sage
II. Calculus with Sage
1. Functions and models
2. Limits and Derivatives
3. Differentiation Rules
4. Applications of Differentiation
5. Integrals
6. Applications of Integration
7. Infinite Sequences and Infinite Series
8. Vectors and the Geometry of Space
9. Vector Functions
10. Partial Derivatives
11. Multiple Integrals
12. Vector Calculus
III. Linear Algebra with Sage
1. Vectors
2. System of Linear Equations
3. Matrices and Matrix Algebra
4. Determinants
5. Linear Transformations
6. Dimension and Structure
7. Diagonalization
8. General Vector Spaces
Appendix : http://matrix.skku.ac.kr/Cal-Book/Appnd/index.htm
1) Sage는 다양한 형태(Sage Notebook, Sage Cell, Sage Cloud)의 웹 서비스(Web Service)로 제공되는데, 일반적으로 Sage Notebook을 Sage라 부른다.
2) Sage에서 수학연산을 실행할 수 있는 각 문서.
3) Maple 인터페이스 : http://www.sagemath.org/doc/reference/sage/interfaces/maple.htmlMATLAB 인터페이스 : http://www.sagemath.org/doc/reference/sage/interfaces/matlab.html
Mathematica 인터페이스 : http://www.sagemath.org/doc/reference/sage/interfaces/mathematica.html
I. Sage Tutorial
written by Prof. Sang-Gu Lee, Dr. Kyung-Won Kim
assisted by Shaowei Sun
1. Introduction
Mathematical tools have long held an important place in the classroom. With the innovation of information and communication technologies(ICT), many tools have appeared and been adapted for educational purposes. Sage is popular mathematical software which was released in 2005. This software has efficient features which can be utilized through the Internet and can handle most mathematical problems, including linear algebra, abstract algebra, combinatorics, number theory, symbolic computation, numerical mathematics and calculus. In this book, we will introduce this powerful software and discuss how it can be used in classes.
Sage is a mathematical Computer Algebra System (CAS) that can be easily used online. The Sage notebook was released in April 2008 at University of Washington, USA. It is free and has powerful capabilities that can be compared with expensive commercial software such as Mathematica, Maple or Matlab. However, it does not require separate installation of the program. It is more like Web-Mathematica, but has some better features. When you connect with any web browser, you can solve almost all calculus problems in the book by using resources that we are offering. You can easily find pre-existing commands to modify for your own problems. The Sage notebook is a platform that allows you to interface with many open-source and commercial programs (if you have a license).
■ Online Sage Servers :
1. http://www.sagenb.org (Sign in)
2. http://math1.skku.ac.kr
3. http://sage.skku.edu (SKKU Sage Cell Server, Mobile)
Sage Community (Left) http://www.sagemath.org
Sage Korean Version (Right) http://math1.skku.ac.kr
Use Firefox or Chrome to connect to one of the above servers. Then register your ID and password to get started.
2005년에 처음 발표된 Sage1)는 서버용 무료 수학연산 프로그램으로서, 사용자의 PC에 직접 설치할 필요가 없이 인터넷 환경만 제공되면 언제 어디서나 사용이 가능하다. 특히 Sage를 이용하여 워크시트(worksheet)2)를 제작하고, 그 워크시트에서 Sage명령과 수학연산에 적합한 파이선(python) 명령어들을 직접 실행해볼 수 있다.
Sage는 기본적으로 웹을 통해 서비스되기 때문에, Sage를 이용하여 제작된 워크시트 또한 웹을 통해 다른 사람들과 공유할 수 있다. 따라서 새로운 수학연산을 시도할 때 그 수학연산에 대한 Sage 명령어의 지식이 부족하다 하더라도, 웹을 통해 이미 공개된 다양한 자료들을 통해 Sage는 그 해법을 제시할 수 있다.
Sage의 수많은 명령어 및 새롭게 개발된 함수들은 구글(Google)3)과 같은 웹 검색 사이트를 이용하여 관련된 검색이 가능하다. 그 명령어들을 단순히 복사하여 붙여 넣는 방식만으로도 새로운 수학연산을 할 수 있다. 또한 이와 같이 다양하게 공개된 워크시트의 자료들을 <표 1>의 주소에서 한 번에 얻을 수도 있다.
위치 |
서버명 |
주 소 |
성균관 대학교 |
Math1 |
|
Math3 |
||
Sagenb |
||
SKKU Sage Cell 1 |
||
SKKU Sage Cell 2 |
||
한국방송통신 |
수학 사이버랩 연산서버 |
|
SAGE |
Alpha |
Sage의 대부분의 명령어 알고리즘들은 새롭게 개발된 것들이 아니라 <표 2>와 같이 이미 지난 40여 년 동안 수학의 각 분야에서 유용하다고 검증된 오픈소스 프로그램들의 함수들이 파이선 형식의 명령어로 다시 종합되었다.
분야 |
오픈소스 수학연산 프로그램 |
Algebra and calculus |
Maxima, SymPy |
High precision arithmetic |
GMP, MPFR, MPFI, quaddouble, Givaro |
Commutative algebra |
Singular |
Number theory |
PARI, NTL, mwrank, ECM, FLINTQS, GMP-ECM |
Exact linear algebra |
LinBox, IML |
Group theory |
GAP |
Scientific computation |
GSL, SciPy, NumPy, cvxopt |
Statistical computation |
R |
Graphics (2d and 3d) |
Matplotlib, Tachyon3d, Jmol |
따라서, 우리는 이와 같이 강력한 수학연산을 제공하는 Sage를 이용하여 제작된 공학적 도구를 사용하여 대수적인 답을 찾을 수 있고 Sage의 상호작용 함수(interact function)를 활용하여 다양한 시뮬레이션을 실행할 수도 있다. 이렇듯 Sage는 한국형 CAS 도구로써 공학적 도구 도입의 단점을 모두 극복하여 새로운 도구의 대안이 될 수 있다. 게다가 이미 Sage의 한글화에 성공하여 언어의 제약도 따르지 않는다. 또한, 새롭게 Sage 명령어를 익히지 않고서도 기존의 CAS 도구(Mathematica, Matlab, Maple 등)들의 언어를 그대로 Sage에서 사용할 수도 있다4).
2. How to Use
우리는 Sage 노트북을 이용하여 계정 단위로 다양한 수학 연산을 실행할 수 있다. 따라서 로그인을 해야지만 서비스를 이용할 수 있기 때문에, 우선 처음에는 계정을 만들어야 한다. <그림 1>은 성균관대학교 수학과에서 운영중인 Sagenb Sage 노트북 서버(http://sagenb.skku.edu)이다. 이를 이용하여 본 절에서는 Sage 노트북을 사용하는 주요 방법을 자세하게 설명한다.
<그림 1> Sagenb SKKU Sage Notebook Server
1) 계정 만들기
① Sage와 호환성이 좋은 구글 크롬 브라우저를 통해 http://sagenb.skku.edu에 접속한 후버튼을 클릭하면 <그림 2>와 같이 Sage 노트북 계정 가입하기 화면을 확인할 수 있다.
<그림 2> Sage 노트북 계정 가입
② 사용자 이름(ID), 사용자 암호, 이메일 주소를 입력한 후 버튼을 누르면 계정을 생성할 수 있고, 이제 생성한 ID, 암호를 이용하여 개인 계정을 이용할 수 있다.
2) Sage 노트북의 메인 화면
위에서 생성한 ID와 암호를 입력한 후 로그인 하면 <그림 3>과 같은 Sage 노트북의 메인 화면을 확인할 수 있다.
<그림 3> Sage 노트북 메인 화면
□ 주요 메뉴 소개
● : Sage 노트북 메인 화면 확인
● : 공개된 워크시트 확인
● : 사용자 암호 및 사용자 정보 설정
● : Sage 노트북 종료
● : 새로운 워크시트 작성
● : Sage 워크시트 파일(sws 형식) 업로드
● : 선택한 Sage 워크시트 다운로드(sws 형식)
3) Sage 노트북의 워크시트 화면
이제 새로운 워크시트를 작성하기 위해 를 누르면 <그림 4>와 같이 워크시트 이름을 입력하는 창을 확인할 수 있다. 이때 적당한 워크시트 이름을 입력한 후
버튼을 클릭하면 <그림 5>와 같이 Sage 명령어를 입력하여 실행시킬 수 있는 Sage 노트북 워크시트 화면을 확인할 수 있다.
<그림 4> Sage 노트북 메인 화면
<그림 5> Sage 노트북 워크시트 화면
□ 주요 메뉴 소개
● : Sage 노트북 메인 화면 확인
● : 공개된 워크시트 확인
● : 사용자 암호 및 사용자 정보 설정
● : Sage 노트북 종료
● : 워크시트 저장, 워크시트 저장 후 종료,
워크시트 저장을 하지 않은채로 종료
● : sws 파일 업로드, 새 워크시트 작성, 현재 워크시트 다운로드,
인쇄, 워크시트 이름 바꾸기, 워크시트 복사, 워크시트 삭제
● : 연산 강제 종료, 워크시트 재시작, 워크시트 저장 후 종료,
Sage
명령어 전부 실행, 결과 숨기기, 결과 보이기, 결과 지우기
● : Sage 노트북 서버에 (활용 할) 각종 파일 업로드
● : Sage, GAP, GP, Python, R 명령어 실행 설정
● : 현재 워크시트를 html 형식으로 공개
4) Sage 명령어의 입력 및 실행
<그림 6>과 같이 빈칸부분에서 Sage 명령어를 입력하고 버튼을 누르면, 그 결과를 확인할 수 있다.
<그림 6> Sage 명령어 실행 전(좌), 실행 후(우)
그리고 마우스를 결과 아래에 위치시키면 <그림 7>과 같이 파란색 선을 확인할 수 있는데, 이때 이 선을 마우스 왼쪽버튼으로 클릭하면 Sage 명령어를 입력할 수 있는 새로운 셀(Cell)을 추가할 수 있다.
<그림 7> 새로운 Sage 셀 추가
또는 파란색 선을 Shift 버튼을 누른채로 마우스 왼쪽버튼으로 클릭하면 <그림 8>과 같이 HTML 설명을 추가할 수 있는 텍스트 박스를 열 수 있다. 이 텍스트 박스에서는 다양한 서식과 수식을 이용하여 설명을 추가할 수 있다. 버튼을 클릭하여 입력한 설명들을 화면에
나타낼 수 있고, 그 설명을 다시 마우스 왼쪽버튼으로 더블 클릭하면 다시 텍스트 박스를 띄워 내용들을 수정 할 수 있다.
<그림 8> HTML 설명을 추가할 수 있는 텍스트 박스
만약 사용법을 잘 모르는 Sage 명령어가 있다면, 그 명령어 뒤에 “?”를 붙이거나 “help(Sage 명령어)” 입력하고 버튼을 누르면 <그림 9>와 같이 해당 Sage 명령어에 대한 자세한 설명을 확인할 수 있다.
<그림 9> Sage 명령어 튜토리얼
그리고 “plot”을 입력한 후 “TAB” 키를 누르면 <그림 10>과 같이 “plot”으로 시작하는 모든 Sage 명령어를 확인할 수 있다. 해당 기능은 잘 생각나지 않는 Sage 명령어를 입력할때나, 비교적 길이가 긴 Sage 명령어를 입력할 때 시간을 줄이는데 매우 효과적이다.
<그림 10> Sage 명령어 자동완성 기능
5) 워크시트 저장 및 공개, 종료
Sage 워크시트를 작성 한 후, 우리는 버튼들을 활용하여 워크시트를 저장시키거나 워크시트를 종료시킬 수 있다. 또한
버튼을 클릭하여(<그림
11> 참조) 해당 내용을 <그림 12>와 같이 HTML 형식으로 웹상에 공개시킬 수 있다. 이 공개된 자료는 별도의 Sage 노트북 서버에 로그인을 하지 않아도 웹 주소의 접속 만으로 확인을 할 수 있다.
<그림 11> 워크시트 공개
<그림 12> 웹상에 공개된 워크시트
3. Basic Sage Codes
http://matrix.skku.ac.kr/Cal-Book/Appnd/index.htm
1) 정의
● 변수 x var(‘x’)
● 벡터 vector([1, 2, 3])
● 벡터함수 vector([2-5*t, 4*t, 1+3*t])
● 행렬 matrix([[1, 2], [3, 4]])
● 값 정의(예: a=3) a=3
● 함수의 정의 f(x)=x^2
2) 벡터와 행렬
● 벡터의 크기 a.norm()
● 벡터의 내적 b.dot_product(a)
● 벡터의 외적 b.cross_product(a)
◆ 행렬식 det(A)
◆ 행렬의 크기 len(A)
◆ 행렬의 고유값 A.eigenvalues()
◆ 행렬의 고유벡터 A.eigenvectors_left()
3) 미분과 적분
● 도함수 diff(f(x), x)
◆ 부정적분 integral(f(x), x)
◆ 에서 적분 integral(f(x), x, a, b)
◆ 이중적분 integral(integral(f(x), (x, 0, 1)), (y, 0, 1))
◆ 삼중적분 integral(integral(integral(f(x), (x, 0, 1)), (y, 0, 1)), (z, 0, 1))
4) 그래프 그리기
● 일반함수(2D) plot(f(x), (x, -4, 4))
● 매개변수함수(2D) parametric_plot((f(x), g(x)), (x, 0, 2*pi))
● 음함수(2D) implicit_plot(f(x)==0, (x, -2, 2), (y, -2, 2))
● 선분(2D) line([(1, 1), (2, 2)], color='red')
● 일반함수(3D) plot3d(f(x, y), (x, -2, 2), (y, -2, 2))
● 매개변수함수(3D) parametric_plot3d((f(x), g(x), h(x)), (x, 0, 2*pi))
● 음함수(3D) implicit_plot3d(f(x, y, z)==5, (x, -3,3), (y,-3,3), (z,-3,3))
● 선분(3D) line([(1, 1, 1), (2, 2, 2)], color='red')
● Contour Plot contour_plot(f(x, y), (x, -1, 1), (y, -1, 1), cmap='hsv', labels=True)
● 벡터필드(2D) plot_vector_field((x+y, x), (x, -3, 3), (y, -3, 3))
● 벡터필드(3D) plot_vector_field3d((0, 0, 1), (x, -3, 3), (y,-3,3), (z,-3,3))
5) 극한
● a에서 극한 limit(f(x), x=a)
● a에서 우극한 limit(f(x), x=a, dir='+')
● a에서 좌극한 limit(f(x), x=a, dir='-')
● 에서의 극한 limit(f(x), x=+oo)
● 에서의 극한 limit(f(x), x=-oo)
6) 기타
● 방정식 풀이 solve(f(x)==0, x)
● 급수() sum((p(n), n, 1, +oo)
● 변수 a의 값 보이기 print a
● 정의된 함수 f 보이기 show(f)
● 조건문 if 조건:
statement(s)
# 조건이 True이면 실행할 명령어
else:
statement(s)
# 조건이 False이면 실행할 명령어
● 반복문 for i in range(10):
print i
# i=0~9 까지 i를 출력
4. Sage Quick References
1) Peter Jipsen, version 1.1 (Basic Math) Latest Version at
http://wiki.sagemath.org/quickref
2) William Stein (Calculus) Sage Version 3.4
http://wiki.sagemath.org/quickref
3) GNU Free Document License, extend for your own use
Translated to Korean language by Sang-Gu Lee and Jae Hwa Lee (Sungkyunkwan University) Korean Version at
http://matrix.skku.ac.kr/2010-Album/Sage-QReference-SKKU.pdf
4) Command line
- Evaluate cell: <shift-enter>
- command<tab>: tries to complete command
- command?<tab>: shows documentation
- command??<tab>: shows source
- a.<tab>i: shows all methods for object a (more: dir(a))
- search_doc('string or regexp'): shows links to docs
- search_src('string or regexp'): shows links to source
- lprint(): toggle LaTeX output mode
- version(): print version of Sage
- Insert cell: click on blue line between cells
- Delete cell: delete content then backspace
5. Related Links for Sage
1) Korean version of Sage
- http://matrix.skku.ac.kr/sage
2) Sage를 이용한 미분적분학 1
- http://matrix.skku.ac.kr/Cal-Book
- http://matrix.skku.ac.kr/Cal-Book/part1/part1.html
3) Sage를 이용한 미분적분학 2
- http://matrix.skku.ac.kr/Cal-Book/part2/part2.html
4) Visual Math with Sage (LA & Calculus)
- http://matrix.skku.ac.kr/2012-LAwithSage/interact
5) Sage를 이용한 선형대수학
- http://matrix.skku.ac.kr/LA-Lab
- http://matrix.skku.ac.kr/cal-lab/SKKU-Cell-Matrix-Calculator.html (행렬계산기)
- http://matrix.skku.ac.kr/2012-album/2012-LA-Lectures.htm
6) Sage를 이용한 수학적 모델링
- http://matrix.skku.ac.kr/2013-Album/2013-MM-Syllabus.htm
- 수학적 모델링 : Power-method, Growth-Model, Supply-Demand-Model,
Accelerator-multiplier-Model, SIR-Model
- http://matrix.skku.ac.kr/MathModeling/Bank-Interest.html
- http://matrix.skku.ac.kr/MathModeling/Power-method.html
- http://matrix.skku.ac.kr/MathModeling/Markov-Chain.html
- http://matrix.skku.ac.kr/MathModeling/Fibonacci-Numbers.html
- http://matrix.skku.ac.kr/MathModeling/Growth-Model.html
- http://matrix.skku.ac.kr/MathModeling/Exponential-Growth-Model.html
- http://matrix.skku.ac.kr/MathModeling/Supply-Demand-Model.html
- http://matrix.skku.ac.kr/MathModeling/Accelerator-multiplier-Model.html
- http://matrix.skku.ac.kr/MathModeling/SIR-Model.html
7) 기타 Sage 참고사이트 for 미분방정식, 이산수학, 정수론, 암호론, 조합론 등
- http://wdjoyner.com/teach/DiffyQ/des-book.pdf
- http://www.sagemath.org/doc/prep/Quickstarts/Graphs-and-Discrete.html
- http://www.sagemath.org/doc/tutorial/tour_numtheory.html
- http://www.sagemath.org/pdf/en/reference/cryptography/cryptography.pdf
- http://www.sagemath.org/doc/reference/combinat
II. Calculus with Sage
based on the Calculus book of Prof. Sang-Gu Lee
collected and rearranged by Dr. Kyung-Won Kim, Shaowei Sun
Chapter 1. Functions and models
1. Graph the functions and
.
var('x') # Define variable "x" A = plot(x^3/8, x, -3, 3, linestyle="--", color='green') # graph the first function B = plot(-1/x, x, -3, 3) # graph the second function C = text("y=x^3/8 ", (3, 4), color='green',fontsize=15) # add the text on given position D = text("y= -1/x",(-1,5), fontsize=15 ) # and set the font of the text show(A+B+C+D, ymax=10, ymin=-10) # display graphs and texts one time |
2. Graph the function
var('x') f1(x) = x f2(x) = 4-x plot(piecewise([[(0, 2), f1], [(2, 4), f2]])) # graph f1 on (0, 2), and f2 on (2, 4) |
Chapter 2. Limits and Derivatives
1. Find the limit: (좌극한),
(우극한)
var( 'x' ) f(x)=(x^2 - 4)/abs(x - 2) print limit(f(x), x=2, dir='minus') # x=2일 때 좌극한 print limit(f(x), x=2, dir='plus') # x=2일 때 우극한 |
-4
4
2. Find if limits exist.
var( 'x' ) f(x)=sin(x)/abs(cos(x)) limit(f(x), x=pi/2) # x=2일 때 극한 |
+Infinity
따라서 극한이 존재하지 않는다.
Chapter 3. Differentiation Rules
1. Find the derivative where
.
var('x') f(x) = x^2 + 4*e^x print diff(f(x), x) # dy/dx |
2*x + 4*e^x
2. Find the equation of the tangent line to the curve at
.
var('x') f(x)=x^2+sqrt(x) df(x)=diff(f(x),x) # 도함수 구하기 y(x)=df(4)*(x-4)+18 # 기울기(df(4))를 구하여 접선의 방정식 구하기 print y(x) p1=plot(f(x),x,0,10, linestyle="--", color='blue') # 함수 f(x) 그리기 p2=plot(y(x),x,0,10, color='red') # 접선 y(x) 그리기 show(p1+p2) # 함수 f(x)와 접선 y(x)를 동시에 보여주기 |
33/4*x - 15
Chapter 4. Applications of Differentiation
1. Find the maximum and minimum of the function on
.
var('x') f(x)=x^3-x solve(diff(f(x))==0, x) # look for the flection points of df ma=max(f(-1/3*sqrt(3)), f(1/3*sqrt(3)), f(-3), f(3)) # find maximum value mi=min(f(-1/3*sqrt(3)), f(1/3*sqrt(3)), f(-3), f(3)) # find minimum value print 'maximum is', ma print 'minimum is', mi |
maximum is 24
minimum is -24
2. Newton’s Method
http://matrix.skku.ac.kr/Mobile-Sage-G/sage-grapher-newton_method.html
Chapter 5. Integrals
1. Draw the graph of and calculate it.
f(x)=5/(1-x^2) P1=plot(f(x), 0.5, sqrt(3)/2, fill="axis") # fill the area between f(x) and x-axis P2=plot(f(x), 0.3, sqrt(3)/2+0.05, color='red') # graph f(x) show(P1+P2) # show P1 and P2 print integral(f(x), x, 1/2, sqrt(3)/2).simplify_full() # integrate f(x) on |
-5/2*log(-sqrt(3) + 2) + 5/2*log(sqrt(3) + 2) - 5/2*log(3)
2. Find the Riemann sum for any function you want with different and different rules. http://matrix.skku.ac.kr/Mobile-Sage-G/sage-grapher-riemann_sum.html
Chapter 6. Applications of Integration
1. Find the area of the region, bounded by the given curves ,
,
,
.
f(x)=x-1 g(x)=5-x^2 p1=plot(f(x),(x,0,2)) # graph p2=plot(g(x),(x,0,2), color='red') # graph show(p1+p2) # show the area |
solve(f(x)==g(x), x) # find the intersection of two curves |
[x == -3, x == 2]
integral(abs(f(x)-g(x)), x, 0, 2) # Set the range by the solution |
22/3
Chapter 8. Infinite Sequences and Infinite Series
1. Find a formula for the general term of the sequence, assuming that the pattern of the first few terms continues.
@interact() def _(n=slider(1, 100, 1)): # slider 만들기 for i in srange(1, n+1, 1): print 5*i-3 # for문을 이용하여 수열 구하기 |
2. Determine the radius of convergence of the series
.
var('n') a(n)=factorial(n)/(n+1) # Determine rho=limit(abs(a(n+1)/a(n)), n=+oo) # Find R=1/rho # Find print 'The radius is ', R |
The radius is 0
Chapter 9. Vectors and the Geometry of Space
1. Draw the surface in
.
var('x, y, z') implicit_plot3d(x+y==5, (x, -5, 5), (y, -5, 5), (z, -5, 5)) # graph |
2. Draw the vectors ,
, and
and find the sum of them.
a=vector([2, -3]) # define a vector a b=vector([-2, -1]) # define a vector b c=vector([6, -5]) # define a vector c plot(a, color='red')+plot(b, color='green')+plot(c, color='blue') # graph three vectors |
a+b+c # find the vector sum of a, b, c |
(6, -9)
3. Find the dot product, cross product of ,
and compute the angle between them.
a=vector([6,-3,4]) b=vector([2,0,-3]) s=b.dot_product(a) # find the dot product of a and b c=b.cross_product(a) # find the cross product of a and b theta=arccos(a.dot_product(b)/(a.norm()*b.norm()))
print 'The dot product is', s print 'The cross product is', c print 'The angle between of a, b is', theta |
The dot product is 0
The cross product is (-9, -26, -6)
The angle between of a, b is 1/2*pi
Chapter 10. Vector Functions.
1. Sketch curves with the vector equation . Indicate with an arrow the direction in which
increases.
var('t') r=vector([cos(2*t), sin(3*t), t]) # Define r(t) C=parametric_plot3d(r, (t, 0, 2*pi),color='green', thickness=2) # Sketch curve t1=pi/10 # location of arrows t2=2*pi/3 t3=5*pi/3 Ar1=arrow3d(r(t=t1), r(t=t1+0.1), color='green') # Draw arrows Ar2=arrow3d(r(t=t2), r(t=t2+0.1), color='green') Ar3=arrow3d(r(t=t3), r(t=t3+0.1), color='green') C+Ar1+Ar2+Ar3 |
2. Find and draw the position vector
and the tangent vector
for the given value of
, where
var('t') x(t)=cos(t) y(t)=t r(t)=(x(t),y(t)) dr(t)=(diff(x(t),t),diff(y(t),t)) dr(t) # |
(-sin(t), 1)
t0=pi/4 p1=r(t0) # Find the startpoint of tangent vector at p2=dr(t0)/abs(dr(t0))+r(t0) # Find the endpoint of tangent vector at p=parametric_plot((x(t), y(t)), (t, 0, 2*pi)) # Sketch curve utv=line([p1, p2], rgbcolor=(1, 0, 0), thickness=2) # Sketch tangent vector show(p+utv) |
3. Find the length of the curve ,
.
var('t') r(t)=(4*t, 3*cos(t), 3*sin(t)) # Define r(t) parametric_plot3d(r(t), (t, -5, 5)) # Sketch curve |
dr=diff(r(t), t) s(t)=sqrt(dr[0]^2+dr[1]^2+dr[2]^2) integral(s(t), t, -5, 5) # length of the curve |
50
Chapter 11. Partial Derivatives
1. Find partial derivatives with respect to and
for the function
.
var('x, y') f(x, y)=24*x*y-7*x^2*y^2 f_x = diff(f(x,y), x, 1) # partial derivatives f_y = diff(f(x,y), y, 1) # partial derivatives print "fx(x,y)=", f_x print "fy(x,y)=", f_y |
fx(x,y)= -14*x*y^2 + 24*y
fy(x,y)= -14*x^2*y + 24*x
2. Laplace’s equation is a classical equation of mathematics which arises in both theory and applications. It governs ideal fluid flow, electrostatic potentials, and the steady-state distribution of heat in a conducting medium. Show that the function is harmonic; that is, they satisfy Laplace’s equation.
var('x, y') u(x, y)=x*(x^2-3*y^2) u_xx=diff(u(x, y), x, 2) # Find u_yy=diff(u(x, y), y, 2) # Find print 'Satisfy Laplace’s equation?', bool( u_xx+u_yy==0 ) # Show that |
Satisfy Laplace’s equation? True
3. Find the equations of the tangent plane and the normal line at the point to the surface
.
var('x, y, z, t') f(x, y, z)=x*exp(y)*cos(z) - z grad_f=f.gradient() # gradient of fx, fy, fz = grad_f # Let grad_f(x, y, z) = (fx, fy, fz) print 'The equation of tangent plane is' print fx(1, 0, 0)*(x-1) + fy(1, 0, 0)*(y-0) + fz(1, 0, 0)*(z-0)==0 # tangent plane |
The equation of tangent plane is
x + y - z - 1 == 0
x1=(x-1)/fx(1, 0, 0)==t # Find normal line equations y1=(y-0)/fy(1, 0, 0)==t z1=(z-0)/fz(1, 0, 0)==t print 'Normal line is' solve(x1, x), solve(y1, y), solve(z1, z) # Find (x(t), y(t), z(t)) |
Normal line is
([x == t + 1], [y == t], [z == -t])
Chapter 12. Multiple Integrals
1. Evaluate the integral .
var('x, y') f(x, y)=x+y^2 integral(integral(f(x, y), x, y, 1), y, 0, 1) # Evaluate given double integal |
5/12
2. Evaluate the integral .
var('x, y, a') assume(a>0 or a<0) # Assume integral(integral(exp(x/y), x, 0, y^2/a), y, 0, a) # Evaluate given double integal |
1/2*a^2
3. Find the volume of .
var('u, v') parametric_plot3d((v*sin(u), v*cos(u), 4-v^2), (u, 0, 2*pi), (v ,0 ,2), |
var('r, t') f=4-r^2 # print 'Volume is', integral(integral(f*r, r, 0, 2), t, 0, 2*pi) # Find the volume |
Volume is 8*pi
4. Draw the surface of the sphere that is inside the cylinder
.
var('x, y, z') sphere = implicit_plot3d(x^2+y^2+z^2==16, (x, -5, 5), (y, -5, 5), (z, -5, 5), cylinder = implicit_plot3d(x^2+y^2==4*y, (x, -5, 5), (y, -5, 5), (z, -5, 5), sphere+cylinder |
5. Find the rectangular coordinates of the point whose cylindrical coordinates are given.
T = Cylindrical('height', ['radius', 'azimuth']) # Define transformation T.transform(radius=2, azimuth=pi/2, height=4) |
(0, 2, 4)
Chapter 13. Vector Calculus
1. Sketch the vector field by drawing a diagram.
var('x, y') plot_vector_field((3, 4), (x, -3, 3), (y, -3, 3), aspect_ratio=1) # Draw the vector field |
2. Evaluate where C is the upper half of the unit circle
.
var('t') parametric_plot((cos(t), sin(t)), (t, 0, pi)) |
integral(1+cos(t)^3*sin(t)^2*sqrt(diff(cos(t), t)^2+diff(sin(t), t)^2), t, 0, pi) # Evaluate |
pi
3. Determine whether or not the vector field is conservative. If it is conservative, find a potential of .
var('x, y, z') F(x, y, z) = (2*x*y, x^2+2*y*z, 5*y^2) P, Q, R = F(x, y, z) # Let curlF = (diff(R, y)-diff(Q, z), diff(P, z)-diff(R, x), diff(Q, x)-diff(P, y)) # Find the curl of print "Conservative?", bool( curlF==F(x, y, z) ) # Show that given vector field F is conservative |
Conservative? False
4. Use Green’s theorem to evaluate the line integral when
and circle
is
with positive orientation.
var('x, y, r, t') p = implicit_plot(x^2+y^2==9, (x, -3, 3), (y, -3, 3), cmap=["red"]) p1 = implicit_plot(x==0, (x,-4,4), (y, -4, 4)) # Sketch p2 = implicit_plot(y==0, (x,-4,4), (y, -4, 4)) # Sketch show(p+p1+p2, aspect_ratio=1) |
integral(integral((diff(x, x)-diff(-y, y))*r, r, 0, 3), t, 0, 2*pi) # Evaluate |
18*pi
III. Linear Algebra with Sage
http://matrix.skku.ac.kr/knou-knowls/cla-sage-reference.htm
based on Linear Algebra with Sage by Prof. Sang-Gu Lee
collected and rearranged by Dr. Kyung-Won Kim
http://matrix.skku.ac.kr/LA-Lab/
Chapter 1. Vectors
1. 벡터합, 스칼라배
의 벡터
,
에 대하여
,
,
를 구하여라.
a=vector([1, 2, -3, 4]) # 벡터 생성, 형식은 vector([성분, 성분, ..., 성분]) b=vector([-2, 4, 1, 0]) print "a=", a print "b=", b print "a+b=", a+b # 벡터의 합 print "a-b=", a-b # 벡터의 차 print "-2*a=", -2*a # 벡터의 스칼라배 |
a= (1, 2, -3, 4)
b= (-2, 4, 1, 0)
a+b= (-1, 6, -2, 4)
a-b= (3, -2, -4, 4)
-2*a= (-2, -4, 6, -8)
2. 벡터의 크기, 거리
의 벡터
,
에 대하여
,
,
를 구하여라.
a=vector([2, -1, 3, 2]) b=vector([3, 2, 1, -4]) print a.norm() # 노름 구하기, 형식은 a.norm() print b.norm() # 노름 구하기 print (a-b).norm() # 거리 구하기 |
3*sqrt(2) # sqrt(2) 는 를 의미한다.
sqrt(30)
5*sqrt(2)
3. 벡터의 내적
의 벡터
,
에 대하여
를 구하여라.
a=vector([2, -1, 3, 2]) b=vector([3, 2, 1, -4]) print "a=", a print "b=", b print a.inner_product(b) # 내적 구하기, 형식은 a.inner_product(b) |
a= (2, -1, 3, 2)
b= (3, 2, 1, -4)
-1
4. 벡터의 정사영
,
에 대하여
위로의
의 정사영
와
에 수직인
의 벡터성분
를 구하여라. (
,
)
x=vector([2, -1, 3]) y=vector([4, -1, 2]) yx=y.inner_product(x) # 벡터 x와 y의 내적 구하기 xx=x.inner_product(x) # 벡터 x와 x의 내적 구하기 p=yx/xx*x # 벡터의 정사영 구하기 w=y-p # 벡터 x에 수직인 y의 벡터 성분 w 구하기 print "x=", x print "y=", y print "p=", p print "w=", w |
x= (2, -1, 3)
y= (4, -1, 2)
p= (15/7, -15/14, 45/14)
w= (13/7, 1/14, -17/14)
5. 점과 평면 사이의 거리
점 에서 평면
에 이르는 거리
를 구하여라.
v=vector([3, -1, 2]) n=vector([1, 3, -2]) d=-6 vn=v.inner_product(n) # 벡터 v와 n의 내적 구하기 nn=n.norm() # 벡터 n의 노름 구하기 Dist=abs(vn+d)/nn # 점과 평면사이의 거리 구하기 print "P=", v print "n=", n print Dist |
P= (3, -1, 2)
n= (1, 3, -2)
5/7*sqrt(14)
따라서 점 에서 평면
에 이르는 거리는
이다.
Chapter 2. System of Linear Equations
1. 첨가행렬
다음 선형연립방정식을 행렬의 곱을 이용하여 나타내고, 첨가행렬을 구하여라.
A=matrix([[1, 1, 2], [2, 4, -3], [3, 6, -5]]) # 3x3 행렬 입력 b=vector([9, 1, 0]) # 상수항 벡터 입력 print A.augment(b) # 첨가행렬 |
[ 1 1 2 9]
[ 2 4 -3 1]
[ 3 6 -5 0]
2. RREF
행렬 의 RREF를 구하라.
A=matrix([[1, 1, 1, 4, 4], [2, 3, 4, 9, 16], [-2, 0, 3, -7, 11]]) # 3x5 행렬 입력 print "A=" print A print "RREF(A)=" print A.rref() # A의 RREF 구하기 |
A=
[ 1 1 1 4 4]
[ 2 3 4 9 16]
[-2 0 3 -7 11]
RREF(A)=
[ 1 0 0 2 -1]
[ 0 1 0 3 2]
[ 0 0 1 -1 3]
3. Gauss-Jordan 소거법 1 (유일한 해)
Gauss-Jordan 소거법을 이용하여 다음 연립방정식의 해를 구하여라.
A=matrix([[2, 4, 6], [2, -1, 1], [3, 0, -1]]) b=vector([18, 8, 3]) print "[A: b] =" print A.augment(b) print "RREF([A: b]) =" print A.augment(b).rref() # 행렬 A와 벡터 b의 첨가행렬의 RREF 구하기 print "x =", A.solve_right(b) # .solve_right( )를 이용하여 구할 수도 있다. |
[A: b] =
[ 2 4 6 18]
[ 2 -1 1 8]
[ 3 0 -1 3]
RREF([A: b]) =
[ 1 0 0 2]
[ 0 1 0 -1]
[ 0 0 1 3]
x = (2, -1, 3)
따라서 주어진 선형연립방정식의 해는 ,
,
이다. 또한, A.solve_right(b) 명령어를 이용하여 해를 구할 수도 있다.
4. Gauss-Jordan 소거법 2 (무수히 많은 해)
Gauss-Jordan 소거법을 이용하여 다음 연립방정식의 해를 구하여라.
A=matrix([[1, 3, -2, 0, 2, 0], [2, 6, -5, -2, 4, -3], [0, 0, 5, 10, 0, 15], [2, 6, 0, 8, 4, 18]]) b=vector([0, -1, 5, 6]) print "[A: b] =" print A.augment(b) print "RREF([A: b]) =" print A.augment(b).rref() # 행렬 A와 벡터 b의 첨가행렬의 RREF 구하기 print "x =", A.solve_right(b) # .solve_right( )를 이용하여 구할 수도 있다. |
[A:b]=
[ 1 3 -2 0 2 0 0]
[ 2 6 -5 -2 4 -3 -1]
[ 0 0 5 10 0 15 5]
[ 2 6 0 8 4 18 6]
RREF([A:b])=
[ 1 3 0 4 2 0 0]
[ 0 0 1 2 0 0 0]
[ 0 0 0 0 0 1 1/3]
[ 0 0 0 0 0 0 0]
(0, 0, 0, 0, 0, 1/3)
따라서 주어진 선형연립방정식의 해는 자유변수 ,
,
에 대하여
,
,
,
,
,
이다. 이와 같이 무수히 많은 해를 갖는 선형연립방정식인 경우에, A.solve_right(b)
명령어는 모든 자유변수에 0을 대입한 해를 찾아준다.
Chapter 3. Matrices and Matrix Algebra
1. 행렬의 덧셈, 스칼라배
일 때,
,
,
는?
A=matrix([[1,2,-4], [-2,1,3]]) B=matrix([[0,1,4], [-1,3,1]]) C=matrix([[1,1],[2,2]]) print "A+B =" print A+B # 행렬의 덧셈 print "2*A =" print 2*A # 행렬의 스칼라배 print "(-1)*C =" print (-1)*C # 행렬의 스칼라배 |
A+B =
[ 1 3 0]
[-3 4 4]
2*A =
[ 2 4 -8]
[-4 2 6]
(-1)*C =
[-1 -1]
[-2 –2]
2. 행렬의 곱셈
행렬 ,
에 대하여
를 구하여라.
A=matrix([[1,2,-1], [3,1,0]]) B=matrix([[-2,1], [0,-3], [2,1]]) print A*B # 행렬의 곱(곱하기 기호(*)를 빼먹지 않도록!) |
[-4 -6]
[-6 0]
3. 전치행렬
다음 행렬들의 전치행렬을 각각 구하여라.
A=matrix([[1,-2,3], [4,5,0]]) B=matrix([[1,2,-4],[3,-1,2],[0,5,3]]) C=matrix([[5,4], [-3,2], [2,1]]) D=matrix([[3,0,1]]) print "A^T =" print A.transpose() # 행렬의 전치행렬 A.transpose() 구하기 print "B^T =" print B.transpose() |
A^T =
[ 1 4]
[-2 5]
[ 3 0]
B^T =
[ 1 3 0]
[ 2 -1 5]
[-4 2 3]
4. 가역행렬
행렬 는 가역인가 비가역인가?
A=matrix([[1, 4, 3], [2, 5, 6], [0, 0, 0]]) A.is_invertible() # 행렬이 가역인지 확인 A.is_invertible() |
False
따라서 행렬 는 비가역행렬이다.
5. 역행렬
행렬 의 역행렬을 구하여라.
A=matrix(2, 2, [3, 5, 1, 2]) print "A =" print A print "inverse of A =" print A.inverse() # AB의 역행렬 구하기, 형식은 A.inverse() |
A =
[3 5]
[1 2]
inverse of A =
[ 2 -5]
[-1 3]
6. 기본행렬
세 가지 기본행 연산에 대응하는 기본행렬들은 다음과 같다.
● : 두 행을 교환한다.
● : 한 행에 영 아닌 상수배를 해서 다른 행에 더한다.
● : 한 행에 영 아닌 상수배를 한다.
# 주의!! Sage의 index는 0부터 시작한다.
# elementary_matrix(n, row1=i, row2=j): i행과 j행을 교환 E1=elementary_matrix(4, row1=1, row2=2) # 기본행렬 r2
# elementary_matrix(n, row1=i, scale=m): i행에 m을 곱한다. E2=elementary_matrix(4, row1=2, scale=-3) # 기본행렬 (-3)*r3
# elementary_matrix(n, row1=i, row2=j, scale=m): j행에 m을 곱하여 i행에 더함 E3=elementary_matrix(4, row1=0, row2=3, scale=7) # 기본행렬 7*r4 + r1
print "E1 =" print E1 print "E2 =" print E2 print "E3 =" print E3 |
E1 =
[1 0 0 0]
[0 0 1 0]
[0 1 0 0]
[0 0 0 1]
E2 =
[ 1 0 0 0]
[ 0 1 0 0]
[ 0 0 -3 0]
[ 0 0 0 1]
E3 =
[1 0 0 7]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
7. RREF를 이용하여 역행렬 구하기
첨가행렬 의 RREF를 이용하여 행렬
의 역행렬을 구하여라.
A=matrix([[1, -1, 2], [-1, 0, 2], [-6, 4, 11]]) I=identity_matrix(3) print "A =" print A AI=A.augment(I).rref() # 첨가행렬 [A: I] 의 RREF 구하기 print "RREF[A: I] =" print AI A2=AI.submatrix(0, 3, 3, 3) # A.submatrix(a, b, c, d) # 행렬의 (a+1, b+1) 성분부터 c개의 행, d개의 열로 이루어진 부분행렬 구하기 print "inverse of A =" print A2 |
A =
[ 1 -1 2]
[-1 0 2]
[-6 4 11]
RREF[A: I] =
[ 1 0 0 8/15 -19/15 2/15]
[ 0 1 0 1/15 -23/15 4/15]
[ 0 0 1 4/15 -2/15 1/15]
inverse of A =
[ 8/15 -19/15 2/15]
[ 1/15 -23/15 4/15]
[ 4/15 -2/15 1/15]
8. 역행렬을 이용하여 연립방정식의 해 구하기
역행렬을 이용하여 다음 연립방정식 의 해를 구하여라.
A=matrix(3, 3, [1, 2, 3, 2, 5, 3, 1, 0, 8]) b=vector([1, 3, -1]) print "x=", A.inverse()*b # 역행렬을 이용한 연립방정식의 해 구하기 print "x=", A.solve_right(b) # .solve_right( )를 이용하여 구할 수도 있다. |
x= (-1, 1, 0)
x= (-1, 1, 0)
따라서 주어진 선형연립방정식의 해는 ,
,
이다.
9 대각선행렬, 단위행렬, 영행렬
다음 대각선행렬 와 단위행렬
, 영행렬
를 구하여라.
,
,
H=diagonal_matrix([-3, -2, 1]) # 대각선행렬: diagonal_matrix([d1, d2, d3]) K=identity_matrix(3) # 단위행렬: identity_matrix(n) J=matrix(2, 2, 0) # 영행렬: matrix(m, n, 0) print "H="; print H print "K="; print K print "J="; print J |
H=
[-3 0 0]
[ 0 -2 0]
[ 0 0 1]
K=
[1 0 0]
[0 1 0]
[0 0 1]
J=
[0 0]
[0 0]
10. 대칭행렬, 반대칭행렬
행렬 는 대칭행렬이고, 행렬
는 반대칭행렬임을 보여라.
A=matrix([[1, 2, 3], [2, 4, 5], [3, 5, 6]]) B=matrix([[0, 1, -2], [-1, 0, 3], [2, -3, 0]]) print bool( A==A.transpose() ) # A가 대칭인지 확인 print bool( B==-B.transpose() ) # B가 반대칭인지 확인 |
True
True
따라서 이므로
는 대칭행렬이고,
이므로
는 반대칭행렬이다.
Chapter 4. Determinants
1. 짝치환, 홀치환
의 치환
의 반전의 총수를 구하여 짝치환인지 홀치환인지 결정하여라.
Permutation([5,1,2,4,3]).inversions() # |
[[0, 1], [0, 2], [0, 3], [0, 4], [3, 4]] # 주의!! index는 0부터 시작
Permutation([5,1,2,4,3]).number_of_inversions() # 반전의 개수 구하기 |
5
Permutation([5,1,2,4,3]).is_even() # 짝치환인지 확인 |
False
따라서 의 치환
은 짝치환이 아니므로 홀치환이다.
2. 행렬식
행렬 의 행렬식을 구하여라.
B=matrix([[1, 2, 3], [-4, 5, 6], [7, -8, 9]]) print B.det() # 행렬식 구하기 |
240
3. 수반행렬
행렬 의 adj
를 구하여라.
A=matrix([[3, -2, 1], [5, 6, 2], [1, 0, -3]]) print A.adjoint() # 수반행렬 구하기 |
[-18 -6 -10]
[ 17 -10 -1]
[ -6 -2 28]
4. 행렬식과 수반행렬을 이용하여 역행렬 구하기
행렬식과 수반행렬을 이용하여 행렬 의 역행렬을 구하여라.
A=matrix([[3, -2, 1], [5, 6, 2], [1, 0, -3]]) dA=A.det() # 행렬식 구하기 adjA=A.adjoint() # 수반행렬 구하기 print "inverse of A = (1/dA)*adjA =" print (1/dA)*adjA # 수반행렬을 이용한 역행렬 구하기 |
inverse of A = (1/dA)*adjA =
[ 9/47 3/47 5/47]
[-17/94 5/47 1/94]
[ 3/47 1/47 -14/47]
5. 특성다항식
행렬 의 특성다항식을 구하여라.
A=matrix([[1, 2, 2], [1, 2, -1], [3, -3, 0]]) print A.charpoly() # A의 특성다항식 구하기 |
x^3 - 3*x^2 - 9*x + 27
6. 고유값, 고유벡터
행렬 의 고유값과 고유벡터를 구하여라.
A=matrix([[1, 2, 2], [1, 2, -1], [3, -3, 0]]) print A.eigenvalues() # A의 고유값 구하기 |
[-3, 3, 3]
A=matrix([[1, 2, 2], [1, 2, -1], [3, -3, 0]]) print A.eigenvectors_right() # A의 고유벡터 구하기: (고유값, [고유벡터], 중복도) |
[(-3, [(1, -1/2, -3/2)], 1), (3, [(1, 0, 1), (0, 1, -1)], 2)]
따라서 행렬 의 고유값의
,
이다. 그리고
에 대응하는
고유벡터는
(
)이고,
에 대응하는 고유벡터는
(
)이다.
Chapter 6. Linear Transformations
1. 선형변환의 표준행렬 1
선형변환 가
일 때,
의 표준행렬을 구하여라.
var('x, y, z') h(x, y, z)=[x+2*y, -x-y, z, x+z] # 함수의 정의 T=linear_transformation(QQ^3, QQ^4, h) # 선형변환 정의, 여기서 스칼라는 유리수 e1=vector([1, 0, 0]) # e2=vector([0, 1, 0]) e3=vector([0, 0, 1]) column_matrix([T(e1), T(e2), T(e3)]) # |
[ 1 2 0]
[-1 -1 0]
[ 0 0 1]
[ 1 0 1]
2. 선형변환의 표준행렬 2, image
선형변환 가
일 때,
의 표준행렬을 이용하여
으로 표시하여라. 그리고
일 때,
를 이용하여
를 구하여라.
var('x, y, z') h(x, y, z)=[x+2*y, -x-y, z, x+z] # 함수의 정의 T=linear_transformation(QQ^3, QQ^4, h) # 선형변환 정의, 여기서 스칼라는 유리수 A=T.matrix(side='right') # 선형변환의 표준행렬을 구하는 Sage 명령어 x0=vector([2, -3, 3]) print "A =" print A print "T(x0) =", T(x0) # 벡터 x0에 대한 image 구하기 print "A*x0 =", A*x0 # 표준행렬과 벡터의 곱 구하기 |
A =
[ 1 2 0]
[-1 -1 0]
[ 0 0 1]
[ 1 0 1]
T(x0) = (-4, 1, 3, 5)
A*x0 = (-4, 1, 3, 5)
3. 선형변환의 kernel, 단사
선형변환 를
로 정의하자.
의 kernel을 구하고,
가 단사인지 확인하여라.
var('x, y, z') U = QQ^3 # 벡터공간 정의 h(x, y, z) = [x+2*y-z, y+z, x+y-2*z] # 선형변환 함수 정의 T = linear_transformation(U, U, h) # 선형변환 생성 print T |
Vector space morphism represented by the matrix:
[ 1 0 1]
[ 2 1 1]
[-1 1 -2]
Domain: Vector space of dimension 3 over Rational Field
Codomain: Vector space of dimension 3 over Rational Field
TK = T.kernel() # kernel을 구하기 print TK |
Vector space of degree 3 and dimension 1 over Rational Field
Basis matrix:
[ 1 –1/3 1/3] # kernel이 span( [1, -1/3, 1/3] )임을 뜻한다.
따라서 이므로 주어진 선형변환
는 단사가 아니다.
또한 아래와 같이 T.is_injective() 함수를 이용하여 주어진 선형변환이 단사인지 알아낼 수도 있다.
print "T is injective?", T.is_injective() # 단사인지 확인 |
T is injective? False
4. 행렬변환, kernel, 단사, 치역, 전사
이라 하자.
는 단사이지만, 전사는 아니다.
U = QQ^2 # 벡터공간 정의 V = QQ^3 # 벡터공간 정의 A = matrix(QQ, [[1, 0], [0, 1], [0, 0]]) # 변환행렬 정의 TA = linear_transformation(U, V, A, side='right') # 선형변환 정의 print TA |
Vector space morphism represented by the matrix:
[1 0 0]
[0 1 0]
Domain: Vector space of dimension 2 over Rational Field
Codomain: Vector space of dimension 3 over Rational Field
print TA.kernel() # kernel 구하기 print "TA is injective?", TA.is_injective() # 단사인지 확인 |
Vector space of degree 2 and dimension 0 over Rational Field
Basis matrix:
[]
TA is injective? True
따라서 이므로 선형변환
는 단사이다.
print TA.image() # 치역 구하기 print "TA is surjective ?", TA.is_surjective() # 전사인지 확인 |
Vector space of degree 3 and dimension 2 over Rational Field
Basis matrix:
[1 0 0]
[0 1 0]
TA is surjective? False
5. 직교행렬
다음 행렬들이 직교행렬임을 확인하여라.
,
A=matrix([[3/5, -4/5], [4/5, 3/5]]) B=matrix([[1/sqrt(3), 1/sqrt(2), 1/sqrt(6)], [1/sqrt(3), -1/sqrt(2), 1/sqrt(6)], [1/sqrt(3), 0, -2/sqrt(6)]]) print "AT*A =" print A.transpose()*A # 직교행렬인지 확인 print "BT*B =" print B.transpose()*B # 직교행렬인지 확인 |
AT*A =
[1 0]
[0 1]
BT*B =
[1 0 0]
[0 1 0]
[0 0 1]
따라서 ,
이므로 행렬
,
는 직교행렬이다.
6. 선형변환의 기하적 의미 1 (ploygon 이미지의 선형변환)
세 점 ,
,
을 지나는 삼각형과 이를 2배로 확대시킨 도형,
축으로 1배만큼 층밀림시킨 도형, 반시계방향으로
만큼 회전시킨 도형을 같이 그리시오.
위 선형변환을 구현하기 위해 우선 아래와 같이 행렬을 이용한 선형변환 함수를 정의한다.
def matrix_transformation(A, L): n=matrix(L).nrows() # list L의 성분의 갯수 L2=[[0,0] for i in range(n)] # 새로운 list L2 정의 for i in range(n): L2[i]=list(A*vector(L[i])) # L2=A*L return L2 # L2 내보내기 print "The matrix_transformation function is activated" # 적용되었는지 확인 |
그리고 문제에 조건에 맞는 표준행렬들을 정의한다.
A=matrix([[2,0], [0,2]]) # 주어진 이미지를 2배로 확대시키는 행렬 B=matrix([[1,1], [0,1]]) # 주어진 이미지를 C=matrix([[cos(pi/3), -sin(pi/3)], [sin(pi/3), cos(pi/3)]]) # 주어진 이미지를 반시계방향으로 pi/3만큼 회전시키는 행렬 |
1) ploygon 함수를 이용하여 세 점 ,
,
을 지나는 삼각형 그린다.
L1=list( [ [0,0], [0,3], [3,0] ]) # 세 점을 입력 SL1=polygon(L1, alpha=0.3, rgbcolor=(1,0,0)) # 위 세 점을 지나는 도형 그리기 SL1.show(aspect_ratio=1, figsize=3) |
2) 주어진 삼각형을 2배로 확대시킨 도형을 그린다.
L2=matrix_transformation(A, L1) # 선형변환을 이용한 새로운 세 점 계산 SL2=polygon(L2, alpha=0.8, rgbcolor=(0,0,1)) # 위 세 점을 지나는 도형 그리기 SL2.show(aspect_ratio=1, figsize=3) |
3) 주어진 삼각형을 축으로 1배만큼 층밀림시킨 도형 그린다.
L3=matrix_transformation(B, L1) # 선형변환을 이용한 새로운 세 점 계산 SL3=polygon(L3, alpha=0.8, rgbcolor=(1,0,1)) # 위 세 점을 지나는 도형 그리기 SL3.show(aspect_ratio=1, figsize=3) |
4) 주어진 삼각형을 반시계방향으로 만큼 회전시킨 도형 그린다.
L4=matrix_transformation(C, L1) # 선형변환을 이용한 새로운 세 점 계산 SL4=polygon(L4, alpha=0.4, rgbcolor=(0,0,1)) # 위 세 점을 지나는 도형 그리기 SL4.show(aspect_ratio=1, figsize=3) |
5) 위의 네 도형들을 동시에 한 화면에 그린다.
(SL1+SL2+SL3+SL4).show(aspect_ratio=1, figsize=3) |
7. 선형변환의 기하적 의미 2 (line 이미지의 선형변환)
평면상에 알파벳 를 그리고, 이를 2배로 확대시킨 도형,
축으로 1배만큼 층밀림시킨 도형, 반시계방향으로
만큼 회전시킨 도형을 그리시오.
위 선형변환을 구현하기 위해 우선 아래와 같이 행렬을 이용한 선형변환 함수를 정의한다.
def matrix_transformation(A, L): n=matrix(L).nrows() # list L의 성분의 갯수 L2=[[0,0] for i in range(n)] # 새로운 list L2 정의 for i in range(n): L2[i]=list(A*vector(L[i])) # L2=A*L return L2 # L2 내보내기 print "The matrix_transformation function is activated" # 적용되었는지 확인 |
그리고 문제에 조건에 맞는 표준행렬들을 정의한다.
A=matrix([[2,0], [0,2]]) # 주어진 이미지를 2배로 확대시키는 행렬 B=matrix([[1,1], [0,1]]) # 주어진 이미지를 C=matrix([[cos(pi/3), -sin(pi/3)], [sin(pi/3), cos(pi/3)]]) # 주어진 이미지를 반시계방향으로 pi/3만큼 회전시키는 행렬 |
1) line 함수를 이용하여 알파벳 S를 그린다.
L1=list( [ [0,0], [4,4], [-3,12], [0,15], [3,12], [4,12], [0,16], [-4,12], [3,4], SL1=line(L1, color="red") # 위 점들을 지나는 도형 그리기 SL1.show(aspect_ratio=1, figsize=5) |
2) 알파벳 S를 2배로 확대시킨 도형을 그린다.
L2=matrix_transformation(A, L1) # 선형변환을 이용한 새로운 점들의 좌표 계산 SL2=line(L2, color="purple") # 위 점들을 지나는 도형 그리기 SL2.show(aspect_ratio=1, figsize=5) |
3) 알파벳 S를 축으로 1배만큼 층밀림시킨 도형 그린다.
L3=matrix_transformation(B, L1) # 선형변환을 이용한 새로운 점들의 좌표 계산 SL3=line(L3, color="blue") # 위 점들을 지나는 도형 그리기 SL3.show(aspect_ratio=1, figsize=5) |
4) 알파벳 S를 반시계방향으로 만큼 회전시킨 도형 그린다.
L4=matrix_transformation(C, L1) # 선형변환을 이용한 새로운 점들의 좌표 계산 SL4=line(L4, color="green") # 위 점들을 지나는 도형 그리기 SL4.show(aspect_ratio=1, figsize=5) |
5) 위의 네 도형들을 동시에 한 화면에 그린다.
(SL1+SL2+SL3+SL4).show(aspect_ratio=1, figsize=5) |
Chapter 7. Dimension and Structure
1. 일차독립
행렬식을 이용한 일차독립 판정법을 이용하여,의 세 벡터
에 대하여
은
일차독립임을 확인하여라.
x1=vector([1, 2, 3]) x2=vector([-1, 0, 2]) x3=vector([3, 1, 1]) A=column_matrix([x1, x2, x3]) # x1, x2, x3를 열벡터로 하는 행렬 생성 print "A=" print A print "det(A) =", A.det() # 행렬 A의 행렬식 구하기 |
A=
[ 1 -1 3]
[ 2 0 1]
[ 3 2 1]
det(A) = 9
따라서 det 이므로
은 일차독립이다.
2. 해공간
다음 동차연립방정식의 해공간을 구하여라.
A=matrix([[4, 12, -7, 6], [1, 3, -2, 1], [3, 9, -2, 11]]) print "Null space of A is", A.right_kernel() # 행렬 A의 해공간 구하기 |
Null space of A is Free module of degree 4 and rank 2 over Integer Ring
Echelon basis matrix:
[ 1 3 4 -2]
[ 0 5 6 -3]
3. Rank, Nullity
행렬 의 rank와 nullity를 구하여라.
A = matrix([[1, -2, 1, 1, 2], [-1, 3, 0, 2, -1], [0, 1, 1, 3, 4], [1, 2, 5, 13, 5]]) print "rank(A) =", A.rank() # rank 구하기 print "nullity(A) =", A.right_nullity() # nullity 구하기 |
rank(A) = 3
nullity(A) = 2
4. Gram-Schmidt 정규직교화
일 때, Gram-Schmidt 정규직교화 과정을 이용하여
의 기저
로부터
의 정규직교기저
를 구하여라.
x1=vector([1,1,0]) x2=vector([0,1,2]) x3=vector([1,2,1]) A=matrix([x1,x2,x3]) # x1, x2, x3를 행벡터로 하는 행렬 생성 print "A=" print A |
A=
[1 1 0]
[0 1 2]
[1 2 1]
[G, mu]=A.gram_schmidt() # 직교화 과정: 행에 대하여 직교기저를 찾는다. A==mu*G print "G=" print G |
G=
[ 1 1 0]
[-1/2 1/2 2]
[-2/9 2/9 -1/9]
N=matrix([G.row(i) / G.row(i).norm() for i in range(0, 3)]) # 정규화과정: 정규화한 직교기저를 행으로 하는 행렬 print "N=" print N |
N=
[ 1/2*sqrt(2) 1/2*sqrt(2) 0]
[-1/3*sqrt(1/2) 1/3*sqrt(1/2) 4/3*sqrt(1/2)]
[ -2/3 2/3 -1/3]
5. 기저의 변환, 전이행렬
,
,
,
일 때 의 두 기저
,
에 대하여 전이행렬
를 구하고,
일 때 좌표벡터
를 구하여라.
우선 전이행렬 를 다음과 같이 구할 수 있다.
x1=vector([1, 2, 0]) x2=vector([1, 1, 1]) x3=vector([2, 0, 1]) A=column_matrix([x1, x2, x3]) # x1, x2, x3를 열벡터로 하는 행렬 생성 y1=vector([3, -1, 4]) y2=vector([7, 1, 1]) y3=vector([6, 1, -4]) B=column_matrix([y1, y2, y3]) # y1, y2, y3를 열벡터로 하는 행렬 생성 print "[ y1: y2: y3: x1: x2: x3 ] =" print B.augment(A) C=B.augment(A).rref() # [ y1: y2: y3: x1: x2: x3 ]의 RREF 구하기 print "RREF([ y1: y2: y3: x1: x2: x3 ]) =" print C P=C.submatrix(0, 3, 3, 3) # A.submatrix(a, b, c, d) # 행렬의 (a+1, b+1) 성분부터 c개의 행, d개의 열로 이루어진 부분행렬 print "P =" print P |
[ y1: y2: y3: x1: x2: x3 ] =
[ 3 7 6 1 1 2]
[-1 1 1 2 1 0]
[ 4 1 -4 0 1 1]
RREF([ y1: y2: y3: x1: x2: x3 ]) =
[ 1 0 0 -7/5 -2/3 1/5]
[ 0 1 0 8/5 1 1/5]
[ 0 0 1 -1 -2/3 0]
P =
[-7/5 -2/3 1/5]
[ 8/5 1 1/5]
[ -1 –2/3 0]
그리고 전이행렬 를 이용하여
를 구할 수 있다.
xa=vector([1, 5, 2]) P*xa |
(-13/3, 7, -13/3)
Chapter 8. Diagonalization (행렬의 대각화)
1. 임의의 순서기저를 갖는 선형변환
선형변환 를
이라 정의하고,
,
를 각각
와
의 순서기저라 하자. 이때
를 구하고,
를 구하여라.
우선 을 다음과 같이 구할 수 있다.
var('x, y') h(x, y) = [2*x+y, x-y, x+4*y] T = linear_transformation(QQ^2, QQ^3, h) x1=vector([0, 1]) x2=vector([1, 0]) y1=vector([0, 0, 1]) y2=vector([0, 1, 0]) y3=vector([1, 0, 0]) B=column_matrix([y1, y2, y3, T(x1), T(x2)]) # 열벡터로 이루어진 행렬 생성 print "[y1: y2: y3: T(x1): T(x2)] =" print B C=B.rref() # [y1: y2: y3: T(x1): T(x2)]의 RREF 구하기 print "RREF[y1: y2: y3: T(x1): T(x2)] =" print C AP=C.submatrix(0, 3, 3, 2) # A.submatrix(a, b, c, d) # 행렬의 (a+1, b+1) 성분부터 c개의 행, d개의 열로 이루어진 부분행렬 print "AP =" print AP |
[y1: y2: y3: T(x1): T(x2)] =
[ 0 0 1 1 2]
[ 0 1 0 -1 1]
[ 1 0 0 4 1]
RREF[y1: y2: y3: T(x1): T(x2)] =
[ 1 0 0 4 1]
[ 0 1 0 -1 1]
[ 0 0 1 1 2]
AP =
[ 4 1]
[-1 1]
[ 1 2]
그리고 를 이용하여
를 구할 수 있다.
xa=vector([6, -4]) # AP*xa |
(20, -10, -2)
2. 행렬의 대각화
행렬 가 대각화가능함을 보이고, 이때
를 대각화하는 행렬
와 대각행렬
를
구하여라.
A=matrix(QQ, [[0, 0, -2], [1, 2, 1], [1, 0, 3]]) A.eigenvalues() # 고유값 구하기 |
[1, 2, 2]
A.eigenvectors_right() # 고유벡터 구하기: (고유값, [ 고유벡터 ], 중복도) |
[(1, [ (1, -1/2, -1/2) ], 1), (2, [ (1, 0, -1), (0, 1, 0) ], 2)]
따라서 행렬 는
개의 일차독립인 고유벡터를 갖는다. 그러므로 행렬
는 대각화 가능이다. 또한 아래와 같이 .is_diagonalizable()
함수를 이용하여 대각화 가능여부를 확인할 수도 있다.
print A.is_diagonalizable() # 대각화 가능 여부 확인 |
True
x1=vector([1, -1/2, -1/2]) # 고유벡터1 정의 x2=vector([1, 0, -1]) # 고유벡터2 정의 x3=vector([0, 1, 0]) # 고유벡터3 정의 P=column_matrix([x1, x2, x3]) # 세 고유벡터를 열벡터로 하는 행렬 print "P=" print P |
P=
[ 1 1 0]
[-1/2 0 1]
[-1/2 -1 0]
print "D=" print P^-1*A*P # 대각화 가능하다면 고유값을 대각원소로 하는 대각행렬 생성됨 |
D=
[1 0 0]
[0 2 0]
[0 0 2]
3. Jordan 표준형
다음 행렬 의 Jordan 표준형을 구하여라.
A=matrix(QQ, [[2, -1, 0, 1], [0, 3, -1, 0], [0, 1, 1, 0], [0, -1, 0, 3]]) print "A is diagonalizable?", A.is_diagonalizable() # 대각화 가능 여부 확인 print "A=" print A print "JCF of A=" A.jordan_form() # Jordan 표준형 |
A is diagonalizable? False
A=
[ 2 -1 0 1]
[ 0 3 -1 0]
[ 0 1 1 0]
[ 0 -1 0 3]
JCF of A=
[3|0 0|0]
[-+---+-]
[0|2 1|0]
[0|0 2|0]
[-+---+-]
[0|0 0|2]
4. 특이값 분해(Singular Value Decomposition)
행렬 의 특이값분해(SVD)를 구하여라.
A=matrix([[sqrt(3), 2], [0, sqrt(3)]]) B=A.transpose()*A C=A*A.transpose() eig=B.eigenvalues() # 고유값 구하기 sv=[sqrt(i) for i in eig] # 특이값 구하기 print sv |
[3, 1]
B.eigenvectors_right() # |
[(9, [(1, sqrt(3))], 1), (1, [(1, -1/3*sqrt(3))], 1)]
G=matrix([[1, sqrt(3)], [1, -1/3*sqrt(3)]]) Vh=matrix([(1/(G.row(j).norm())) * G.row(j) for j in range(0, 2)]) Vh=Vh.simplify() # print Vh |
[ 1/2 1/2*sqrt(3)]
[1/2*sqrt(3) -1/2]
C.eigenvectors_right() # |
[(9, [(1, 1/3*sqrt(3))], 1), (1, [(1, -sqrt(3))], 1)]
F=matrix([[1, 1/3*sqrt(3)], [1, -sqrt(3)]]) U=matrix([(1/(F.row(j).norm())) * F.row(j) for j in range(0,2)]) U=U.simplify().transpose() # print U |
[ 1/2*sqrt(3) 1/2]
[ 1/2 -1/2*sqrt(3)]
S=diagonal_matrix(sv) # print "S=" print S print "U*S*Vh=A?", bool(U*S*Vh==A) # |
S=
[3 0]
[0 1]
U*S*Vh=A? True
5. Pseudo-inverse (일반화된 역행렬)
행렬 의 Pseudo-inverse를 구하여라.
A=matrix([[1, 1], [0, 1], [1, 0]]) print "A=" print A print "Pseudo-inverse of A=" print (A.transpose()*A).inverse()*A.transpose() # Pseudo-inverse 구하기 |
A=
[1 1]
[0 1]
[1 0]
Pseudo-inverse of A=
[ 1/3 -1/3 2/3]
[ 1/3 2/3 –1/3]
Chapter 9. General Vector Spaces
1. Conjugate
벡터 의 conjugate를 구하여라.
u=vector([1, 2-I, -3+2*I]) # I 는 허수단위 print "u =", u print "u2 =", u.conjugate() # 벡터 u의 conjugate 구하기 |
u = (1, -I + 2, 2*I - 3)
u2 = (1, I + 2, -2*I – 3)
2. 복소공간에서의 내적과 거리
벡터 의 유클리드 내적과 유클리드 거리를 구하여라.
u=vector([2*I, 0, 1+3*I]) # I 는 허수단위 v=vector([2-I, 0, 1+3*I]) print v.hermitian_inner_product(u) # 유클리드 내적 구하기 # 앞에 오는 벡터에 대하여 켤레복소수를 취한다 # < u, v > = v.hermitian_inner_product(u) |
4*I + 8
(u-v).norm() # 유클리드 거리 구하기 |
sqrt(13)
3. Wronskian
Wronskian을 이용하여 ,
,
일 때, 세 함수가 일차독립임을 보여라.
wronskian(1, e^x, e^(2*x)) # Wronskian(f1(x), f2(x), f3(x)) 구하기 |
2*e^(3*x)
이므로 이 세 함수들의 집합은 일차독립이다.
부록 : http://matrix.skku.ac.kr/Cal-Book/Appnd/index.htm
< 수학을 위한 소프트웨어 >
<Pioneers of Korean Modern Mathematics>
http://matrix.skku.ac.kr/K-Math-History/index.htm
written by Sang-Gu Lee with Kyung-Won Kim
based on Books of Prof. Sang-Gu Lee (Calculus and Linear Algebra with Sage)
collected and rearranged by Kyung-Won Kim, Shaowei Sun and Sang-Gu Lee
by