# Tactiverge Academy — companion code for "Sampling rate and aliasing"
# Lesson: https://tactiverge.win/academy/embedded-systems/sensor-integration/sampling-and-aliasing/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import math

fs = 10.0                                  # samples per second
for n in range(6):
    t = n / fs
    fast = math.cos(2 * math.pi * 9 * t)   # a 9 Hz signal
    slow = math.cos(2 * math.pi * 1 * t)   # a 1 Hz signal
    print(f"t = {t:.1f} s   9 Hz: {fast:+.3f}   1 Hz: {slow:+.3f}")


# ── Example 2 ────────────────────────────────────────
def alias_frequency(f, fs):
    """Frequency that a sine of f Hz appears to have when sampled at fs Hz."""
    k = round(f / fs)           # nearest whole multiple of fs
    return abs(f - k * fs)

for f, fs in [(9, 10), (3, 10), (50, 40), (60, 50), (100, 1000)]:
    print(f"{f:4d} Hz sampled at {fs:4d} Hz looks like {alias_frequency(f, fs):g} Hz")
