def colored_noise_generator(D, lamb, dt):
"""
An iterable generator function for colored noise.
:param D: Amplitude of the noise
:param lamb: Reciprocal of the characteristic time
:param dt: Time step
:return : yields the successive value
"""
e_0 = None
E = exp(-lamb * dt)
while True:
if e_0 is None:
# Create the first value
n, m = np.random.uniform(0.0, 1.0, 2)
e_0 = sqrt(-2 * D * lamb * log(m)) * cos(2 * pi * n)
yield e_0
else:
# Create succession
a, b = np.random.uniform(0.0, 1.0, 2)
h = sqrt(-2 * D * lamb * (1 - E ** 2) * log(a)) * cos(2 * pi * b)
e_next = e_0 * E + h
e_0 = e_next
yield e_0
def colored_vector(D, lamb, dt, vec):
"""
Ads colored noise to the given vector.
This function uses the colored_noise_generator() generator function
:param D: amplitude of the noise
:param lamb: reciprocal of the characteristic time
:param dt: time step
:param vec: the vector to extend with noise
:return: the given vector with noise
"""
# Create color generator
noise_generator = colored_noise_generator(D, lamb, dt)
# iterate through vec and add noise then return the list
return [x + noise_generator.next() for x in vec]
def count(start=0, step=1):
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) -> 2.5 3.0 3.5 ...
n = start
while True:
yield n
n += step
from itertools import count
def generate_primes(stop_at=0):
primes = []
for n in count(2):
if 0 < stop_at < n:
return # raises the StopIteration exception
composite = False
for p in primes:
if not n % p:
composite = True
break
elif p ** 2 > n:
break
if not composite:
primes.append(n)
yield n
for i in generate_primes(): # iterate over ALL primes
if i > 100:
break
print(i)