<jupyter_start><jupyter_text>내삽법Interpolation 예를 들어 실험을 통해 얻은 두 측정값 사이의 값을 추정하고 싶을 경우, 내삽법을 시도해 볼 수 있다.For instance, to guess values between two measurements, we may try interpolation. 아래의 표를 살펴보자.Let's take a look at the following table.<jupyter_code># Import NumPy and matplotlib
import pylab as py


# Import pandas for tables
import pandas as pd

# What is this?
py.seed()

# Parameters
a = 0.5
b = 1.5

# x array
x_array = py.arange(5+0.5)

# True values of y
y_true = a * x_array + b

# contamination
noise = py.random(x_array.shape) - 0.5

# Measurement values
y_measurement = y_true + noise

# Organize data in table form
# https://stackoverflow.com/questions35160256
df = pd.DataFrame(
    {'$x$':x_array, '$y_{true}$':y_true, '$y_{measurement}$':y_measurement}, 
    columns=['$x$', '$y_{true}$', '$y_{measurement}$'],
)

# Plot data points
ax = df.plot.line(x='$x$', y='$y_{true}$')
df.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{measurement}$')

py.show()


# Present the table
df<jupyter_output><empty_output><jupyter_text>여기서 $0 \le x \le 1$ 구간의 $y$ 값을 알아보자.Let's try to figure out $y$ values in the $0 \le x \le 1$ interval.  선형 내삽Linear interpolation 두 점 $(x_1, y_1)$, $(x_2, y_2)$ 을 지나는 직선의 방정식을 구할 수 있다.We can formulate the straight line passing two points of $(x_1, y_1)$ and $(x_2, y_2)$.<jupyter_code># Import symbolic processor module
import sympy as sy

# Initialize printing equations
sy.init_printing()


# Declare symbols
x = sy.symbols('x')

# Multiple symbols using `:`
x1, x2 = sy.symbols('x1:3')
y1, y2 = sy.symbols('y1:3')

# Define slope
slope = (y2 - y1) / (x2 - x1)

# Define the straight line
y_interp = slope * (x - x1) + y1

# Present the equation
y_interp<jupyter_output><empty_output><jupyter_text>($0 \le x \le 1$ 구간에서) 임의의 $x_i$ 에 대응되는 $y_i$ 는 다음과 같이 구할 수 있다.We can find $y_i$ for an arbitrary $x_i$ (within $0 \le x \le 1$ interval) as follows.<jupyter_code># Declared x_i as a SymPy symbol
x_i = sy.symbols('x_i')

# Prepared a dictionary containing substitution pairs
substitution_dict = {
    # "substitute x with x_i"
    x: x_i,
    x1: x_array[0],
    x2: x_array[1],
    y1: y_measurement[0],
    y2: y_measurement[1],
}

# Substitution
y_i_sy = y_interp.subs(substitution_dict)

# Result of substitution
y_i_sy<jupyter_output><empty_output><jupyter_text>프로그래밍 언어 구문을 생성하는 것도 가능하다.SymPy may generate expressions in programming languages.<jupyter_code>python_code = sy.python(y_interp)
print(python_code)


c_code = sy.ccode(y_interp)
print(c_code)


fortran_code = sy.fcode(y_interp)
print(fortran_code)<jupyter_output><empty_output><jupyter_text>보통 `interp()` 함수를 이용한다.Usually we call `interp()` function.<jupyter_code># x values to interpolate
x_i = py.linspace(x_array[0], x_array[-1], 50+1)

# Interpolate
y_i = py.interp(x_i, x_array, y_measurement)


# Plot data points
ax = df.plot.line(x='$x$', y='$y_{true}$')
df.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{measurement}$')

# Plot interpolation
ax.plot(x_i, y_i, '.', label='$y_{interp}$')

# Show legend table
py.legend(loc=0)

py.show()<jupyter_output><empty_output><jupyter_text>`pandas` 판다스의 데이터프레임도 간단한 내삽 기능이 있다.`DataFrame` of `pandas` also has simple interpolation features.<jupyter_code>df_interp_nan = df.reindex(x_i)


# http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.interpolate.html
df_interp = df_interp_nan.interpolate(method='linear')


# Plot data points
ax = df.plot.line(x='$x$', y='$y_{true}$')
# Plot interpolation
df_interp.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{interp}$', c='orange')
df.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{measurement}$')

# Show legend table
py.legend(loc=0)

py.show()<jupyter_output><empty_output><jupyter_text>다음은 $y_{measurement}$ 의 히스토그램을 그린 것이다.Following shows a histogram of $y_{measurement}$.<jupyter_code>df_interp['$y_{measurement}$'].hist()<jupyter_output><empty_output><jupyter_text>3차 스플라인 곡선Cubic spline curve [스플라인](https://en.wiktionary.org/wiki/spline)은 얇고 긴 나무자를 말한다. 부드러운 곡선을 그리기 위해 사용했었다.A [spline](https://en.wiktionary.org/wiki/spline) is a ruler made of a piece of thin and long rectangular wood.  Drafters used it draw a smooth curve. 여기서 "3차"는 내삽할 때 3차 다항식을 사용한다는 의미이다."Cubic" here means that we would interpolate using a 3rd order polynomial. $$y = a_0 x^3 + a_1 x^2 + a_2 x + a_3$$  SciPy<jupyter_code># https://www.scipy-lectures.org/intro/scipy.html#interpolation-scipy-interpolate

# Import interpolation subpackage
import scipy.interpolate as sn

cubic_interp = sn.interp1d(x_array, y_measurement, kind='cubic')
y_cubic = cubic_interp(x_i)


# Plot data points
ax = df.plot.line(x='$x$', y='$y_{true}$')
df.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{measurement}$')

# Plot linear interpolation
ax.plot(x_i, y_i, '.', label='$y_{linear}$')

# Plot cubic spline curve
ax.plot(x_i, y_cubic, 'x', label='$y_{cubic}$')

# Show legend table
py.legend(loc=0)

py.show()<jupyter_output><empty_output><jupyter_text>pandas<jupyter_code># http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.interpolate.html
df_interp = df_interp_nan.interpolate(method='cubic')


# Plot data points
ax = df.plot.line(x='$x$', y='$y_{true}$')
# Plot interpolation
df_interp.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{interp}$', c='orange')
df.plot.scatter(x='$x$', y='$y_{measurement}$', ax=ax, label='$y_{measurement}$')

# Show legend table
py.legend(loc=0)

py.show()<jupyter_output><empty_output><jupyter_text>연습문제Exercises 도전 과제 1 : $0(^\circ)$ ~ $360(^\circ)$ 구간에서 10도 간격으로 $sin \theta^\circ $ 값의 표를 만들어 보시오.Try this 1 : Make a table of $sin \theta^\circ$ within $0(^\circ)$ ~ $360(^\circ)$ with interval of 10 degrees. 도전 과제 2 : 위 표의 값을 이용하여 1도 간격으로 $sin \theta^\circ$ 값을 추정하시오.Try this 2 : Estimate  $sin \theta^\circ$ values with interval of 1 degree using the values of the table above.  Final Bell마지막 종<jupyter_code># stackoverfow.com/a/24634221
import os
os.system("printf '\a'");<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1602447494625434, 'fraction_numerical': 0.016702497106002977, 'mean_word_length': 5.406779661016949, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 41, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '180043', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2771, 'n_tokens_neox': 2837, 'n_words': 588, 'path': '00_interpolation.ipynb', 'repo_name': 'kangwonlee/19ECA-20-interpolation', 'size': '6047'}