Assignment 3
과제 3
과제 | 3 |
---|---|
점수 | 0 |
제출 | False |
이번 내용은 짧지만 매우 중요합니다. 꼭 천천히 읽으면서 따라해보세요.
(과제 2의 연습문제 해설은 5주차에 업로드 됩니다.)
0. 들어가며
여러분은 무리수 \(\pi\)를 소수점 아래 몇번째 자리수까지 외울 수 있나요? 아마 그렇게 많이 외울수는 없을거에요. 하지만, 테일러급수를 이용하면 \(\pi\)를 계산할 수 있어요. \(x\in[-1, 1]\)에서 \(\arctan\)의 테일러급수는 다음과 같습니다.
\[\arctan(x) = \sum_{n=0}^{\infty} {(-1)^{n}\frac{x^{(2n+1)}}{2n+1}} = x - \frac{x^3}{3} + \frac{x^5}{5} - \cdots, \quad -1 \le x \le 1.\]또한, 우리는 \(\arctan(1)=\frac{\pi}{4}\)인 걸 알고있기 때문에,
\[\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \cdots,\]이죠. 이것을 이용해서 직접 \(\pi\)를 계산해볼까요?
MATLAB codes
x = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + 1/17;
PI = 4 * x;
fprintf("PI = %.6f\n", PI);
MATLAB results
PI = 3.252366
어떤가요? 9번째 항까지 전개했지만, 우리가 예상한 \(\pi\)의 값 \(3.141592\dots\)와는 많이 다른 걸 알 수 있습니다. 만약 우리가 더 많은 항까지 전개하여 계산한다면, 더 정확한 결과를 얻을 수 있을거에요. 이런 경우에 직접 손으로 계산하는 건 한계가 있겠죠? 이럴때 for
문과 while
문을 이용해서 해결할 수 있습니다.
1. for
반복문
for
반복문은
for <변수> = <범위>
<코드(변수)>
end
의 형태로 사용할 수 있습니다. <변수>
가 <범위>
의 처음부터 마지막까지 순차적으로 변화하는 동안, <변수>
와 관련된 코드가 작동하는 것이지요. 간단한 예를 보겠습니다.
for i = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
fprintf("변수는 %d 입니다.\n", i);
end
변화하는 변수에 맞춰서 메시지가 출력됩니다. 만약 :
구문을 이용한다면, 더 간단하게 바꿀 수 있습니다.
for i = 1:10
fprintf("변수는 %d 입니다.\n", i);
end
그렇다면 이제 for
문을 이용해 \(\pi\)의 값을 계산해봅시다.
MATLAB codes
pi_4 = 0;
for i = 0:10^5
pi_4 = pi_4 + (-1)^i / (2 * i + 1);
end
PI = pi_4 * 4;
fprintf("PI = %.6f\n", PI)
MATLAB results
PI = 3.141603
무려 \(10^5\)째 항까지 계산했더니, 드디어 우리가 아는 \(\pi\)의 값과 비슷한 결과를 얻었습니다. 지금보니, 처음에 손으로 계산하려 한 것은 어림없는 시도였던 것이죠. 하지만, 우리는 아직도 만족할 수 없어요. 지금 얻은 결과조차도 실제 \(\pi\)와 비교하면 꽤 큰 오차가 있기 때문입니다.
2. while
반복문
for
문을 이용해서 \(\pi\)의 값을 계산할때, 가장 어려운 것 중에 하나는 바로 <범위>
를 정하는 것 입니다. 몇 번째 항까지 계산해야 원하는만큼 정확한 \(\pi\)의 값을 구해낼 수 있을지 모르기 때문이죠. 사실 수학을 이용해서 조금만 분석해보면, \(n\)번째 항까지 계산했을 때 실제 \(\pi\)와의 오차가 어느정도인지 대략적으로 계산해낼 수 있습니다만, 그건 이 문서의 범위를 넘어서므로 다루지 않겠습니다. 대신 (아마도?)더 간단하게, while
문을 이용해서 원하는 만큼 정확한 값을 구해내보죠. while
문은,
while <조건>
<코드>
end
와 같은 구조를 가집니다. 언뜻 보기엔 for
문보다 더 간단해 보이는데요. 반복 횟수가 정해져있는 for
문과는 달리, while
문은 <조건>
을 만족하는 동안은 계속해서 <코드>
를 반복 실행 합니다. 예를들어,
i = 0;
while i < 10
i = i + 1;
fprintf("변수는 %d 입니다.\n", i);
end
와 같이 사용할 수 있죠. 다시 \(\pi\)를 구하는 문제로 돌아가 보겠습니다. 우리는 err
변수를 정의해서, err
가 원하는 값보다 작아져야 반복을 그만두는 코드를 작성할 것입니다. 이 과정에서, 우리가 알고있는 \(\pi\)의 값을 사용해서 err
를 계산하겠습니다.
MATLAB codes
err = 999; % set initial error
pi_4 = 0;
pi_4_real = 3.1415926535 / 4; % (approx) real value of pi / 4
i = 0;
while err >= 10^(-8) % while `err` is not small enough
pi_4 = pi_4 + (-1)^i / (2 * i + 1);
err = abs(pi_4 - pi_4_real);
i = i + 1;
end
PI = 4 * pi_4;
fprintf("PI = %.6f, order = %d\n", PI, i);
이제 \(\pi\)의 값을 소수점 7번째 자리까지 정확히 계산한 결과를 얻을 수 있습니다. 또한, 그러기까지 무려 24943984번째 항까지 전개를 해야한다는 것도 알 수 있네요. 이처럼, while
문을 사용하면 for
문으로는 해결하기 힘든 경우도 해결할 수 있습니다.
연습문제
-
그래프를 그려서 다음 극좌표계의 교점의 개수를 찾으세요.
\[\begin{cases} r = 1+\cos(k\theta)\\ r = \cos(k\theta)\\ \end{cases}, \qquad \text{where} \quad 0\le\theta\le 2\pi\]- 매트랩의
hold
명령어를 사용해서 하나의 극좌표계에 두개의 그래프를 동시에 나타내세요. - 각각의 \(k = 1, 2, \cdots, 6\) 에 대하여 1번의 과정을 반복하세요.
for
문을 이용하여 쉽게 해결할 수 있습니다. - 2번에서의 각 \(k\)에 대한 결과를 하나의 figure창에 나타내세요. \(2\times 3\)
subplot
들을 생성해서 해결하세요.
각각 몇개의 교점을 가지고 있습니까?
- 매트랩의
Assignment 3
Assignment | 3 |
---|---|
Score | 0 |
Submission | False |
This is short, but very important. Please read carefully and follow along.
(The solution of the exercise of the last week will be uploaded in week 5.)
0. Intro
How many digits can you memorize the irrational number \(\pi\)? Maybe you can’t memorize that much. However, we can calculate \(\pi\) using the Taylor series. The Taylor series of \(\arctan\) where \(x\in[-1, 1]\) is:
\[\arctan(x) = \sum_{n=0}^{\infty} {(-1)^{n}\frac{x^{(2n+1)}}{2n+1}} = x - \frac{x^3}{3} + \frac{x^5}{5} - \cdots, \quad -1 \le x \le 1.\]and since we know that \(\arctan(1)=\frac{\pi}{4}\),
\[\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \cdots,\]Now, shall we use this to calculate \(\pi\)?
MATLAB codes
x = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + 1/17;
PI = 4 * x;
fprintf("PI = %.6f\n", PI);
MATLAB results
PI = 3.252366
We expanded to the 9th term, but we can see that it is very different from the value of \(\pi\) we expected \(3.141592\dots\). If we expand to more terms than 9th term, we will get more accurate result. But in that case, it is hard to calculate by hand coding. Thus we can use the for
statement and the while
statement.
1. for
loop
In general, for
loop looks like:
for <variable> = <range>
<codes(variable)>
end
While <variable>
changes sequentially from the beginning to the end of the <range>
, the code related to <variable>
is executed. Let’s look at a simple example.
for i = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
fprintf("The variable is %d.\n", i);
end
A message is displayed according to the changing variable i
. If we use the :
syntax, we can change it more simply.
for i = 1:10
fprintf("The variable is %d.\n", i);
end
Then, let’s use the for
statement to calculate the value of \(\pi\).
MATLAB codes
pi_4 = 0;
for i = 0:10^5
pi_4 = pi_4 + (-1)^i / (2 * i + 1);
end
PI = pi_4 * 4;
fprintf("PI = %.6f\n", PI)
MATLAB results
PI = 3.141603
After calculating up to the \(10^5\)th term, we finally got a result similar to the value of \(\pi\) we know. Now we know that it was almost impossible to try to get accurate results by hand coding. But, we still can’t be satisfied. Because we want to calculate a more accurate value.
2. while
loop
When calculating the value of \(\pi\) using the for
statement, one of the most difficult things is determining the <range>
. It’s because we don’t know if we need to calculate the number of terms to get the exact value of \(\pi\) as we want. In fact, if we analyze it a bit using math, we can roughly calculate how much the error is from the actual \(\pi\) when calculating to the \(n\)th term, but that is beyond the scope of this document, so I will not deal with it. Instead, we can use the while
statement.
while <condition>
<codes>
end
The while
loop is looks like above. At first glance, it looks simpler than the for
statement. Unlike the for
statement, which has a fixed number of iterations, the while
statement executes <code>
repeatedly as long as the <condition>
is satisfied.
i = 0;
while i < 10
i = i + 1;
fprintf("The variable is %d.\n", i);
end
You can use it as above. Let’s go back to the problem of finding \(\pi\). We’ll define a variable err
, so we’ll write the code to stop loop if err
is less than the desired value. In this process, we will calculate err
using the value of \(\pi\) we know.
MATLAB codes
err = 999; % set initial error
pi_4 = 0;
pi_4_real = 3.1415926535 / 4; % (approx) real value of pi / 4
i = 0;
while err >= 10^(-8) % while `err` is not small enough
pi_4 = pi_4 + (-1)^i / (2 * i + 1);
err = abs(pi_4 - pi_4_real);
i = i + 1;
end
PI = 4 * pi_4;
fprintf("PI = %.6f, order = %d\n", PI, i);
Now we can get the exact result of calculating the value of \(\pi\) to the 7th decimal place. In addition, it can be seen that in order to do so, it must be expanded to the 24943984th term. Like this, using the while
statement can solve cases that are difficult to solve with the for
statement.
Exercise
-
Find the number of intersections of the polar system
\[\begin{cases} r = 1+\cos(k\theta)\\ r = \cos(k\theta)\\ \end{cases}, \qquad \text{where} \quad 0\le\theta\le 2\pi\]by drawing the polar curves in MATLAB.
- For a polar system, use the MATLAB command
hold
to graph two polar curves on the same set of axis. - For \(k = 1, 2, \cdots, 6\), graph the polar curves of each polar systems. You may use
for
loop. Then, you will have 6 graphs because you have 6 polar systems. - Display your resulting images with \(2 \times 3\) subplots in the same figure window.
How many intersections are there in each system?
- For a polar system, use the MATLAB command
Leave a comment