0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AD変換関連計算用

Last updated at Posted at 2024-07-11
import numpy as np
import matplotlib.pyplot as plt

# サンプルデータの生成
fs = 1000  # サンプリング周波数 (Hz)
t = np.arange(0, 1, 1/fs)  # 時間配列
f = 50  # 信号周波数 (Hz)
signal = np.sin(2 * np.pi * f * t)  # サイン波信号
noise = np.random.normal(0, 0.1, len(t))  # 白色ノイズ
adc_output = signal + noise  # ADC出力信号

# 量子化ノイズの計算
quantization_levels = 256  # 8ビットADCの場合
quantization_step = 2 / quantization_levels  # 量子化ステップ
quantized_signal = np.round(adc_output / quantization_step) * quantization_step
quantization_noise = adc_output - quantized_signal

# 微分非直線性誤差 (DNL) の計算
dnl = np.diff(quantized_signal) - quantization_step
dnl_max = np.max(dnl)
dnl_min = np.min(dnl)

# 積分非直線性誤差 (INL) の計算
inl = np.cumsum(dnl)
inl_max = np.max(inl)
inl_min = np.min(inl)

# 信号対雑音比 (SNR) の計算
signal_power = np.mean(signal**2)
noise_power = np.mean(noise**2)
snr = 10 * np.log10(signal_power / noise_power)

# 信号対雑音および歪み比 (SNDR) の計算
signal_plus_noise_power = np.mean(adc_output**2)
snr_plus_distortion = 10 * np.log10(signal_power / (signal_plus_noise_power - signal_power))

# スプリアスフリー動的レンジ (SFDR) の計算
fft_signal = np.fft.fft(adc_output)
fft_magnitude = np.abs(fft_signal)
sfdr = 10 * np.log10(np.max(fft_magnitude[1:]) / np.max(fft_magnitude[2:]))

# 有効ビット数 (ENOB) の計算
enob = (snr - 1.76) / 6.02

# 雑音エネルギーの計算
noise_energy = np.sum(noise**2)

# 熱雑音の計算
k = 1.38e-23  # ボルツマン定数 (J/K)
T = 300  # 温度 (K)
R = 50  # 抵抗 (Ω)
thermal_noise_power = k * T * fs / R

# 全ノイズ電力の計算
total_noise_power = noise_power + thermal_noise_power

# Figure of Merit (FoM) の計算
fom = snr * (2**enob)

# プロット
plt.figure(figsize=(14, 10))

# サイン波信号
plt.subplot(3, 2, 1)
plt.plot(t, signal, label='Signal')
plt.title('Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)

# ノイズ
plt.subplot(3, 2, 2)
plt.plot(t, noise, label='Noise', color='r')
plt.title('Noise')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)

# ADC出力信号
plt.subplot(3, 2, 3)
plt.plot(t, adc_output, label='ADC Output', color='g')
plt.title('ADC Output')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)

# 量子化信号
plt.subplot(3, 2, 4)
plt.plot(t, quantized_signal, label='Quantized Signal', color='m')
plt.title('Quantized Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)

# 量子化ノイズ
plt.subplot(3, 2, 5)
plt.plot(t, quantization_noise, label='Quantization Noise', color='c')
plt.title('Quantization Noise')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)

plt.tight_layout()
plt.show()

# 結果の表示
print(f"DNL: Max = {dnl_max:.4f}, Min = {dnl_min:.4f}")
print(f"INL: Max = {inl_max:.4f}, Min = {inl_min:.4f}")
print(f"SNR: {snr:.2f} dB")
print(f"SNDR: {snr_plus_distortion:.2f} dB")
print(f"SFDR: {sfdr:.2f} dB")
print(f"ENOB: {enob:.2f} bits")
print(f"量子化ノイズ: {np.mean(quantization_noise**2):.4f}")
print(f"雑音エネルギー: {noise_energy:.4f}")
print(f"SN比: {snr:.2f} dB")
print(f"熱雑音: {thermal_noise_power:.4e} W")
print(f"全ノイズ電力: {total_noise_power:.4e} W")
print(f"FoM: {fom:.2f}")


image.png

import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft

# パラメータ設定
Fs = 1000  # サンプリング周波数 (Hz)
Fin = 50   # 入力信号の周波数 (Hz)
duration = 1  # 期間 (秒)
t = np.linspace(0, duration, int(Fs*duration), endpoint=False)  # 時間軸

# サイン波生成
amplitude = 1
signal = amplitude * np.sin(2 * np.pi * Fin * t)

# 雑音の追加
noise_amplitude = 0.1  # 雑音の振幅
noise = noise_amplitude * np.random.normal(size=t.shape)
noisy_signal = signal + noise

# 8ビットAD変換
def adc_8bit(signal):
    quantized_signal = np.round((signal + 1) * (2**7)) / (2**7) - 1
    return quantized_signal

# 10ビットAD変換
def adc_10bit(signal):
    quantized_signal = np.round((signal + 1) * (2**9)) / (2**9) - 1
    return quantized_signal

# FFTによるパワースペクトル計算
def calculate_power_spectrum(signal, Fs):
    N = len(signal)
    yf = fft(signal)
    xf = np.fft.fftfreq(N, 1/Fs)[:N//2]
    power_spectrum = 2.0/N * np.abs(yf[:N//2])**2
    return xf, power_spectrum

# SNR計算
def calculate_snr(signal, Fs):
    xf, power_spectrum = calculate_power_spectrum(signal, Fs)
    signal_power = np.sum(power_spectrum[(xf >= Fin-1) & (xf <= Fin+1)])
    noise_power = np.sum(power_spectrum) - signal_power
    snr = 10 * np.log10(signal_power / noise_power)
    return snr

# SQNR計算
def calculate_sqnr(signal, quantized_signal):
    signal_power = np.mean(signal**2)
    quantization_noise_power = np.mean((signal - quantized_signal)**2)
    sqnr = 10 * np.log10(signal_power / quantization_noise_power)
    return sqnr

# SNDR計算
def calculate_sndr(signal, Fs):
    xf, power_spectrum = calculate_power_spectrum(signal, Fs)
    signal_power = np.sum(power_spectrum[(xf >= Fin-1) & (xf <= Fin+1)])
    total_noise_power = np.sum(power_spectrum) - signal_power
    sndr = 10 * np.log10(signal_power / total_noise_power)
    return sndr

# AD変換後の信号
adc_8bit_signal = adc_8bit(noisy_signal)
adc_10bit_signal = adc_10bit(noisy_signal)

# パワースペクトル計算
xf, power_spectrum_8bit = calculate_power_spectrum(adc_8bit_signal, Fs)
_, power_spectrum_10bit = calculate_power_spectrum(adc_10bit_signal, Fs)

# SNR計算
snr_8bit = calculate_snr(adc_8bit_signal, Fs)
snr_10bit = calculate_snr(adc_10bit_signal, Fs)

# SQNR計算
sqnr_8bit = calculate_sqnr(noisy_signal, adc_8bit_signal)
sqnr_10bit = calculate_sqnr(noisy_signal, adc_10bit_signal)

# SNDR計算
sndr_8bit = calculate_sndr(adc_8bit_signal, Fs)
sndr_10bit = calculate_sndr(adc_10bit_signal, Fs)

# 結果をコンソールに表示
print(f"8ビットAD変換のSN比 (SNR): {snr_8bit:.2f} dB")
print(f"10ビットAD変換のSN比 (SNR): {snr_10bit:.2f} dB")
print(f"8ビットAD変換の量子化雑音比 (SQNR): {sqnr_8bit:.2f} dB")
print(f"10ビットAD変換の量子化雑音比 (SQNR): {sqnr_10bit:.2f} dB")
print(f"8ビットAD変換の信号対歪雑音比 (SNDR): {sndr_8bit:.2f} dB")
print(f"10ビットAD変換の信号対歪雑音比 (SNDR): {sndr_10bit:.2f} dB")

# 結果表示
plt.figure(figsize=(14, 10))

# オリジナル信号とAD変換信号のプロット
plt.subplot(3, 1, 1)
plt.plot(t, noisy_signal, label='Noisy Signal')
plt.plot(t, adc_8bit_signal, label='8-bit ADC Signal', linestyle='--')
plt.plot(t, adc_10bit_signal, label='10-bit ADC Signal', linestyle='-.')
plt.legend()
plt.title('Noisy Signal and ADC Converted Signals')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')

# 8ビットAD変換信号のパワースペクトル
plt.subplot(3, 1, 2)
plt.plot(xf, power_spectrum_8bit)
plt.title(f'Power Spectrum of 8-bit ADC Signal\n'
          f'SNR: {snr_8bit:.2f} dB, SQNR: {sqnr_8bit:.2f} dB, SNDR: {sndr_8bit:.2f} dB')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Power')

# 10ビットAD変換信号のパワースペクトル
plt.subplot(3, 1, 3)
plt.plot(xf, power_spectrum_10bit)
plt.title(f'Power Spectrum of 10-bit ADC Signal\n'
          f'SNR: {snr_10bit:.2f} dB, SQNR: {sqnr_10bit:.2f} dB, SNDR: {sndr_10bit:.2f} dB')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Power')

plt.tight_layout()
plt.show()

image.png

import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft

# パラメータ設定
Fs = 1000  # サンプリング周波数 (Hz)
Fin = 50   # 入力信号の周波数 (Hz)
duration = 1  # 期間 (秒)
t = np.linspace(0, duration, int(Fs*duration), endpoint=False)  # 時間軸

# サイン波生成
amplitude = 1
signal = amplitude * np.sin(2 * np.pi * Fin * t)

# 8ビットAD変換
def adc_8bit(signal):
    quantized_signal = np.round((signal + 1) * (2**7)) / (2**7) - 1
    return quantized_signal

# 量子化信号
quantized_signal = adc_8bit(signal)

# 量子化誤差
quantization_error = signal - quantized_signal

# FFTによるパワースペクトル計算
def calculate_power_spectrum(signal, Fs):
    N = len(signal)
    yf = fft(signal)
    xf = np.fft.fftfreq(N, 1/Fs)[:N//2]
    power_spectrum = 2.0/N * np.abs(yf[:N//2])**2
    return xf, power_spectrum

# オリジナル信号のFFT
xf, power_spectrum_original = calculate_power_spectrum(signal, Fs)

# 量子化誤差のFFT
_, power_spectrum_error = calculate_power_spectrum(quantization_error, Fs)

# 結果表示
plt.figure(figsize=(14, 10))

# オリジナル信号と量子化信号のプロット
plt.subplot(3, 1, 1)
plt.plot(t, signal, label='Original Signal')
plt.plot(t, quantized_signal, label='8-bit Quantized Signal', linestyle='--')
plt.legend()
plt.title('Original Signal and 8-bit Quantized Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')

# 量子化誤差のプロット
plt.subplot(3, 1, 2)
plt.plot(t, quantization_error)
plt.title('Quantization Error')
plt.xlabel('Time [s]')
plt.ylabel('Error Amplitude')

# 量子化誤差のパワースペクトル
plt.subplot(3, 1, 3)
plt.plot(xf, power_spectrum_error)
plt.title('Power Spectrum of Quantization Error')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Power')

plt.tight_layout()
plt.show()

image.png

import numpy as np
import matplotlib.pyplot as plt

# Parameters
Fs = 1000  # Sampling frequency (Hz)
T = 1  # Signal duration (seconds)
t = np.linspace(0, T, Fs * T, endpoint=False)  # Time axis
amplitude = 2  # Signal amplitude
input_signal = amplitude * np.sin(2 * np.pi * 5 * t)  # Input signal (e.g., 5Hz sine wave)
quantization_levels = 8  # Number of quantization levels (e.g., 8-bit ADC)
LSB = 2 * amplitude / (2 ** quantization_levels)  # Least significant bit (LSB)

# Quantization
quantized_signal = np.round(input_signal / LSB) * LSB

# Quantization error (quantization noise)
quantization_error = input_signal - quantized_signal

# Add thermal noise
k = 1.38e-23  # Boltzmann constant
T_resistor = 300  # Temperature in Kelvin
R = 1000  # Resistance in Ohms
thermal_noise_voltage_density = np.sqrt(4 * k * T_resistor * R)
thermal_noise = thermal_noise_voltage_density * np.random.normal(0, 1, len(t))

# Combined noise (quantization noise + thermal noise)
combined_noise = quantization_error + thermal_noise

# Oversampling
oversampling_factor = 4
oversampled_signal = np.repeat(input_signal, oversampling_factor)
oversampled_time = np.linspace(0, T, Fs * T * oversampling_factor, endpoint=False)
quantized_oversampled_signal = np.round(oversampled_signal / LSB) * LSB
quantization_error_oversampled = oversampled_signal - quantized_oversampled_signal

# Add thermal noise to oversampled signal
thermal_noise_oversampled = thermal_noise_voltage_density * np.random.normal(0, 1, len(oversampled_time))
combined_noise_oversampled = quantization_error_oversampled + thermal_noise_oversampled

# FFT function
def compute_fft(signal, Fs):
    N = len(signal)
    fft_vals = np.fft.fft(signal)
    fft_freqs = np.fft.fftfreq(N, 1/Fs)
    fft_vals = np.abs(fft_vals[:N//2]) / N
    fft_freqs = fft_freqs[:N//2]
    return fft_freqs, fft_vals

# Compute FFT for each signal
fft_input_freqs, fft_input_vals = compute_fft(input_signal, Fs)
fft_quantized_freqs, fft_quantized_vals = compute_fft(quantized_signal, Fs)
fft_combined_noise_freqs, fft_combined_noise_vals = compute_fft(combined_noise, Fs)
fft_oversampled_freqs, fft_oversampled_vals = compute_fft(oversampled_signal, Fs * oversampling_factor)
fft_combined_noise_oversampled_freqs, fft_combined_noise_oversampled_vals = compute_fft(combined_noise_oversampled, Fs * oversampling_factor)

# Plotting
plt.figure(figsize=(15, 12))

# FFT of input signal
plt.subplot(5, 1, 1)
plt.plot(fft_input_freqs, fft_input_vals, label='Input Signal FFT')
plt.legend()
plt.title('FFT of Input Signal')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')

# FFT of quantized signal
plt.subplot(5, 1, 2)
plt.plot(fft_quantized_freqs, fft_quantized_vals, label='Quantized Signal FFT')
plt.legend()
plt.title('FFT of Quantized Signal')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')

# FFT of combined noise (quantization noise + thermal noise)
plt.subplot(5, 1, 3)
plt.plot(fft_combined_noise_freqs, fft_combined_noise_vals, label='Combined Noise FFT')
plt.legend()
plt.title('FFT of Combined Noise (Quantization Noise + Thermal Noise)')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')

# FFT of oversampled signal
plt.subplot(5, 1, 4)
plt.plot(fft_oversampled_freqs, fft_oversampled_vals, label='Oversampled Signal FFT')
plt.legend()
plt.title('FFT of Oversampled Signal')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')

# FFT of combined noise in oversampled signal
plt.subplot(5, 1, 5)
plt.plot(fft_combined_noise_oversampled_freqs, fft_combined_noise_oversampled_vals, label='Combined Noise in Oversampled Signal FFT')
plt.legend()
plt.title('FFT of Combined Noise in Oversampled Signal')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude')

plt.tight_layout()
plt.show()

image.png

import numpy as np
import matplotlib.pyplot as plt

# パラメータ設定
fs = 1000  # サンプリング周波数
t = np.arange(0, 1, 1/fs)
analog_signal = np.sin(2 * np.pi * 50 * t)

# 量子化
n_bits = 6
quantization_levels = 2**n_bits
quantized_signal = np.round(analog_signal * quantization_levels) / quantization_levels

# 量子化誤差
quantization_error = analog_signal - quantized_signal

# 量子化誤差の実効値(RMS)
rms_error = np.sqrt(np.mean(quantization_error**2))
print(f"量子化誤差の実効値 (RMS): {rms_error}")

# 量子化誤差の頻度分布をプロット
plt.figure(figsize=(12, 6))
plt.hist(quantization_error, bins=30, edgecolor='k')
plt.title('Quantization Error Distribution')
plt.xlabel('Quantization Error')
plt.ylabel('Frequency')
plt.show()

# SN比の計算
signal_power = np.mean(analog_signal**2)
noise_power = np.mean(quantization_error**2)
snr = 10 * np.log10(signal_power / noise_power)
print(f"SN比: {snr} dB")

# サンプリングクロックジッタの影響をシミュレート
jitter_std = 1e-4  # ジッタの標準偏差
jitter = np.random.normal(0, jitter_std, size=t.shape)
t_jittered = t + jitter

# ジッタを含む信号のサンプリング
analog_signal_jittered = np.sin(2 * np.pi * 50 * t_jittered)
quantized_signal_jittered = np.round(analog_signal_jittered * quantization_levels) / quantization_levels
quantization_error_jittered = analog_signal_jittered - quantized_signal_jittered

# プロット
plt.figure(figsize=(12, 6))
plt.subplot(3, 1, 1)
plt.plot(t, analog_signal, label='Analog Signal')
plt.plot(t, analog_signal_jittered, label='Analog Signal with Jitter', linestyle='dashed')
plt.legend()

plt.subplot(3, 1, 2)
plt.plot(t, quantized_signal, label='Quantized Signal')
plt.plot(t, quantized_signal_jittered, label='Quantized Signal with Jitter', linestyle='dashed')
plt.legend()

plt.subplot(3, 1, 3)
plt.plot(t, quantization_error, label='Quantization Error')
plt.plot(t, quantization_error_jittered, label='Quantization Error with Jitter', linestyle='dashed')
plt.legend()

plt.show()

# ジッタのある信号のSN比
noise_power_jittered = np.mean(quantization_error_jittered**2)
snr_jittered = 10 * np.log10(signal_power / noise_power_jittered)
print(f"ジッタのある信号のSN比: {snr_jittered} dB")




image.png

import numpy as np

# 初期設定
VREF = 1.0  # 参考電圧
Ain = 0.6   # 入力電圧(例として0.6Vを使用)
N = 10      # ビット数(Nを変更可能)

# 初期条件
REF = [VREF]
D = []  # デジタル出力を保存するリスト

# シミュレーション
for i in range(1, N + 1):  # Nビットのため、1からNまで
    if Ain > REF[-1]:
        D.append(1)
        next_ref = REF[-1] + (1 / 2**i) * VREF
        threshold_expr = f'REF{i-1} + (1 / 2**{i}) * VREF'
    else:
        D.append(0)
        next_ref = REF[-1] - (1 / 2**i) * VREF
        threshold_expr = f'REF{i-1} - (1 / 2**{i}) * VREF'
    
    REF.append(next_ref)
    
    # 各ステージの出力を表示
    print(f'Stage {i}: REF = {REF[-1]:.12f}, D = {D[-1]}')
    print(f'Calculation: REF{i} = {threshold_expr}')

# デジタル出力の計算
digital_output = sum(d * 2**(N-i) for i, d in enumerate(D))
print(f'\nDigital Output: {digital_output} (Binary: {bin(digital_output)[2:].zfill(N)})')



import matplotlib.pyplot as plt

def fibonacci(n):
    fib_seq = [1, 1]
    while len(fib_seq) < n:
        fib_seq.append(fib_seq[-1] + fib_seq[-2])
    return fib_seq

def ratio_convergence(fib_seq):
    ratios = [fib_seq[i+1] / fib_seq[i] for i in range(2, len(fib_seq) - 1)]
    return ratios

# フィボナッチ数列の長さ
n = 20
fib_seq = fibonacci(n)

# 隣接する2項の商
ratios = ratio_convergence(fib_seq)

# 結果の表示
print("Fibonacci Sequence:", fib_seq)
print("Ratios of consecutive terms:", ratios)

# グラフの描画
plt.figure(figsize=(10, 5))
plt.plot(range(2, n-1), ratios, marker='o', linestyle='-', color='b')
plt.axhline(y=1.618, color='r', linestyle='--', label='Golden Ratio (approx.)')
plt.title('Convergence of Ratios in Fibonacci Sequence')
plt.xlabel('Index')
plt.ylabel('Ratio')
plt.legend()
plt.grid(True)
plt.show()



import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft, fftfreq

# 1. アナログ信号の生成
Fs = 1000  # サンプリング周波数 (Hz)
T = 1 / Fs  # サンプリング間隔
L = 1000  # サンプル数

# 時間ベクトル
t = np.linspace(0.0, L*T, L, endpoint=False)

# アナログ信号(例: サイン波 + 高調波成分)
f1 = 50  # 基本周波数 (Hz)
f2 = 150  # 高調波周波数 (Hz)
signal = 0.7 * np.sin(2 * np.pi * f1 * t) + 0.3 * np.sin(2 * np.pi * f2 * t)

# 2. ノイズの追加
np.random.seed(0)  # 再現性のためにシードを設定
noise = 0.1 * np.random.normal(size=t.shape)
signal_noisy = signal + noise

# 3. FFTによる周波数解析
yf = fft(signal_noisy)
xf = fftfreq(L, T)[:L//2]

# 4. コーヒレントサンプリング
# プロット範囲を制限するためのインデックス
N = 512
xf_coherent = xf[:N//2]
yf_coherent = 2.0 / L * np.abs(yf[:N//2])

# 5. プロット
plt.figure(figsize=(12, 6))

# ノイズを追加したアナログ信号のプロット
plt.subplot(2, 1, 1)
plt.plot(t, signal_noisy, label='Noisy Signal')
plt.title('Analog Signal with Noise')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.legend()

# FFT結果のプロット
plt.subplot(2, 1, 2)
plt.plot(xf_coherent, yf_coherent, label='FFT of Noisy Signal')
plt.title('FFT of Noisy Signal')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()

# 6. S/N比の計算(簡単な例)
signal_power = np.mean(signal**2)
noise_power = np.mean(noise**2)
snr = 10 * np.log10(signal_power / noise_power)
print(f'S/N Ratio: {snr:.2f} dB')

# 7. ハーモニックディストーションの計算(簡単な例)
# 基本周波数成分の強度を求める
fundamental_power = yf_coherent[np.argmax(xf_coherent == f1)]
harmonic_power = yf_coherent[np.argmax(xf_coherent == f2)]
distortion = 10 * np.log10(harmonic_power / fundamental_power)
print(f'Harmonic Distortion: {distortion:.2f} dB')
import numpy as np
import matplotlib.pyplot as plt

# パラメータ設定
Fs = 1000  # サンプリング周波数 (Hz)
T = 1.0 / Fs  # サンプリング間隔 (秒)
L = 2  # 信号の長さ (秒)
t = np.linspace(0.0, L, int(L * Fs), endpoint=False)

# アナログ信号の作成
f_signal = 5  # 信号周波数 (Hz)
analog_signal = 0.5 * np.sin(2 * np.pi * f_signal * t)

# 二重積分型AD変換器のパラメータ
integration_time = 0.01  # 積分時間 (秒)
num_samples = len(t)

# 積分結果の計算
def double_integral(signal, dt, integration_time):
    """二重積分の計算"""
    num_points = int(integration_time / dt)
    integral1 = np.cumsum(signal) * dt
    integral2 = np.cumsum(integral1) * dt
    return integral2[:num_samples]

# 二重積分
digital_signal = double_integral(analog_signal, T, integration_time)

# 正規化
digital_signal /= np.max(np.abs(digital_signal))

# プロット
plt.figure(figsize=(12, 6))

# アナログ信号
plt.subplot(2, 1, 1)
plt.plot(t, analog_signal)
plt.title('Analog Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')

# デジタル信号
plt.subplot(2, 1, 2)
plt.plot(t, digital_signal)
plt.title('Digitized Signal (Double Integral)')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid(True)

plt.tight_layout()
plt.show()



import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter, freqz

# サンプル・ホールド回路のパラメータ
sampling_rate = 1000  # サンプリング周波数 (Hz)
hold_time = 0.01  # ホールド時間 (秒)
fs = 2000  # サンプル周波数 (Hz)
n = 4  # フィルタの次数

# 周波数応答の計算
def sample_and_hold_response(f, hold_time, fs):
    """サンプル・ホールド回路の周波数応答を計算する"""
    T = 1 / fs
    H = np.zeros_like(f)
    
    # ホールド時間に基づく応答
    for i, freq in enumerate(f):
        H[i] = np.abs(np.sinc(freq * hold_time))
    
    return H

# 周波数ベクトルの生成
frequencies = np.linspace(0, sampling_rate / 2, 500)
response = sample_and_hold_response(frequencies, hold_time, sampling_rate)

# プロット
plt.figure(figsize=(10, 6))

plt.plot(frequencies, 20 * np.log10(response), label='Sample and Hold Response')
plt.title('Sample and Hold Circuit Frequency Response')
plt.xlabel('Frequency [Hz]')
plt.ylabel('Magnitude [dB]')
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt

# sinc関数の定義
def sinc(x):
    """sinc関数の定義"""
    return np.sinc(x / np.pi)  # scipyのsinc関数はπを含む

# xの範囲を定義
x = np.linspace(-10, 10, 1000)
y = sinc(x)

# 増減表の計算
dy_dx = np.gradient(y, x)  # 増減率(勾配)を計算
increase = dy_dx > 0
decrease = dy_dx < 0

# プロット
plt.figure(figsize=(12, 6))

# sinc関数のプロット
plt.subplot(2, 1, 1)
plt.plot(x, y, label='sinc(x)')
plt.title('sinc(x) Function')
plt.xlabel('x')
plt.ylabel('sinc(x)')
plt.grid(True)
plt.legend()

# 増減表のプロット
plt.subplot(2, 1, 2)
plt.plot(x, dy_dx, label='sinc(x) Derivative', color='r')
plt.fill_between(x, dy_dx, where=increase, color='green', alpha=0.3, label='Increasing')
plt.fill_between(x, dy_dx, where=decrease, color='red', alpha=0.3, label='Decreasing')
plt.title('sinc(x) Derivative (Increase/Decrease)')
plt.xlabel('x')
plt.ylabel('Derivative')
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?