from IPython.display import Audio
import matplotlib.pyplot as plt
import numpy as np
fact_cache = [1]
def factorial(x):
while len(fact_cache) <= x:
fact_cache.append(len(fact_cache) * fact_cache[-1])
return fact_cache[x]
def sin_unoptimized(x, num_iterations=100):
sin_nth_deriv = lambda n_: (n_ & 1) * (1 - (((n_ >> 1) & 1) << 1))
return sum(sin_nth_deriv(n) * (x ** n) / factorial(n) for n in range(num_iterations))
def cos_unoptimized(x, num_iterations=100):
cos_nth_deriv = lambda n_: (1 - (n_ & 1)) * (1 - (((n_ >> 1) & 1) << 1))
return sum(cos_nth_deriv(n) * (x ** n) / factorial(n) for n in range(num_iterations))
def newton_raphson(f, df, start=0, num_iterations=100):
approx = start
for _ in range(num_iterations):
approx -= f(approx) / df(approx)
return approx
pi = newton_raphson(sin_unoptimized, cos_unoptimized, start=3)
f"PI Approximation: {pi}"
'PI Approximation: 3.1415926535897936'
def optimize_trig_parameter(x):
if x < 0:
x = -x, -1
approx = int(x / (2 * pi)) * 2 * pi
return x - approx, 1
def sin_val(x):
x, invert = optimize_trig_parameter(x)
return invert * sin_unoptimized(x)
def cos_val(x):
x, _ = optimize_trig_parameter(x)
return cos_unoptimized(x)
sin = np.vectorize(sin_val)
cos = np.vectorize(cos_val)
amplitude = 0.5
seconds = 10
sample_rate = 10000
base = np.arange(1, sample_rate * seconds)
frequency = 440
frequency = periods / sec
period = 2pi / c
$\text{frequency of } sin(cx) = \frac{rc}{2 \pi}$
len(base)
99999
def get_frequency(frequency):
c = (frequency * 2 * pi) / sample_rate
wavelet_ = amplitude * sin(c * base)
return wavelet_
a = get_frequency(440)
c_sharp = get_frequency(554.37)
e = get_frequency(659.255)
# g = get_frequency(783.991)
$\text{Octave higher = 2x frequency}$
A3 220.00
A#3/Bb3 233.08
B3 246.94
C4 261.63
C#4/Db4 277.18
D4 293.66
D#4/Eb4 311.13
E4 329.63
F4 349.23
F#4/Gb4 369.99
G4 392.00
G#4/Ab4 415.30
A4 440.00
A#4/Bb4 466.16
wavelet = a + c_sharp
Audio(wavelet, rate=sample_rate)
plt.plot(test[:1000], test_sin[:1000])
[<matplotlib.lines.Line2D at 0x1671d0550>]