跳至主要內容

標籤「數學」的 3 篇文章

查看所有標籤

0.248 (16) 轉換成十進位分數的簡單解法 (基本資訊技術人員考試)

· 1 分鐘閱讀

「16 進位的小數 0.248 轉換成十進位的分數是什麼?」的問題,我將簡單介紹解法。

重點

16 進位的問題使用 2 進位

步驟

  1. 將 16 進位轉換成 2 進位
    0.248(16) = 0.0010 0100 1000(2)

  2. 去掉小數點
    0.0010 0100 1000(2) = 0.0010 0100 1000(2) × 0010 0000 0000(2) / 0010 0000 0000(2) = 0100 1001(2) / 0010 0000 0000(2)

  3. 將 2 進位轉換成 10 進位
    0100 1001(2) / 0010 0000 0000(2) = (64 + 8 + 1) / 512
    = 73 / 512

在 Python 偵測極值

· 2 分鐘閱讀

摘要

偵測訊號的極值。

訊號的產生

舉例產生一個偽造的訊號。

  • 3 [Hz] 的訊號 + 0.01 [Hz] 的訊號 + 雜訊
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import signal

t = np.arange(30 * 100) / 100
x = np.sin(2 * np.pi * t / 3) + np.random.randn(len(t)) * 0.2 + np.sin(2 * np.pi * t / 100)
df = pd.DataFrame({'Data': x}, index=pd.to_datetime(t, unit='s').time)

fig, ax = plt.subplots()
df.plot(ax=ax, xlim=['00:00:00', '00:00:10'])
plt.show()

tmp

檢查訊號的特性

def acorr(df: pd.DataFrame, ra: int = 3, fs=100):
x = np.correlate(df.Data.values, df.Data.values, mode='full')
t = (np.arange(len(x)) - len(x) / 2 + 0.5) / fs
x /= x.max()
fig, ax = plt.subplots()
ax.set_xlim(-ra, ra)
ax.set_ylim(0, 1)
ax.plot(t, x)
ax.set_title('Autocorrelation')
ax.grid(axis='x')
ax.set_xticks(np.linspace(-ra, ra, 2 * ra + 1))
plt.show()

acorr(df)

可以看出主要的訊號是 1/3 [Hz]。因此,對 1/3 [Hz] 施加低通濾波器。

tmp

套用低通濾波器並偵測極值

套用低通濾波器以便偵測極值。

如果在 1/3 [Hz] 施加低通濾波器仍無法正確偵測,請逐步降低頻率。

tmp

fs = 10
lpf = 0.1
b, a = signal.butter(5, lpf / fs * 2, 'low')
df['Filter'] = signal.filtfilt(b, a, df.Data.values)
max_idx = signal.argrelmax(df['Filter'].values)
min_idx = signal.argrelmin(df['Filter'].values)

df['max_index'] = False
df.iloc[max_idx[0], 2] = True
df['min_index'] = False
df.iloc[min_idx[0], 3] = True

fig, ax = plt.subplots()
df.plot(ax=ax)
ax.set_xlim(['00:00:00', '00:00:30'])
ax.scatter(
df.loc[df['max_index'], ['Filter']].index,
df.loc[df['max_index'], ['Filter']],
color='tab:orange',
zorder=3)
ax.scatter(
df.loc[df['min_index'], ['Filter']].index,
df.loc[df['min_index'], ['Filter']],
color='tab:green',
zorder=3)
plt.show()

NMF (HALS) 的實作

· 1 分鐘閱讀
import numpy as np

X = np.array([[1, 1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])

n_components, n_samples, n_features, = (2,) + X.shape
W = np.random.uniform(size = (n_samples, n_components))
H = np.random.uniform(size = (n_components, n_features))

eps = 1e-4

# NMF
for i in range(100):
# update B
A = X.T.dot(W)
B = W.T.dot(W)
for j in range(n_components):
tmp = H[j, :] + A[:, j] - H.T.dot(B[:, j])
H[j, :] = np.maximum(tmp, eps)

# update A
C = X.dot(H.T)
D = H.dot(H.T)
for j in range(n_components):
tmp = W[:, j] * D[j, j] + C[:, j] - W.dot(D[:, j])
W[:, j] = np.maximum(tmp, eps)
norm = np.linalg.norm(W[:, j])
if norm > 0:
W[:, j] /= norm

print(W)
print(H)
print(W.dot(H))