Reputation: 47
I have a function shown below
f(t) = 1 : if 2t rounded down to the next lowest integer is even
f(t) = -1 : if 2t rounded down to the next lowest integer is odd
I am trying to eventually carry out fourier transformations on the function but first I need to write a program to create an array of N=1000 elements containing 1000 equally spaced samples from a single cycle of this function which is a square wave.
How do I create this array ?
Upvotes: 1
Views: 6861
Reputation: 738
As you ask for the values of the square function within a cycle, first you have to create the values for the time samples. Starting at t=0
the function you mentioned has a cycle of 1, after t=1
the function repeates itself.
For creating a sequence of equally spaced values between 0 and 1 there are several alternatives, but a straitght one is numpy.linspace. The first parameter is the starting time of the cycle, the second the end of the cycle and the third the number of samples (equally spaced). By using this you create the t_samples
.
After that you just need to feed the square wave function (square_func
in the code below) with the values stored in t_samples
.
See an example here of how you can use it:
import numpy
def square_func(t):
if int(2*t)%2 == 0:
return 1
else:
return -1
t_samples = numpy.linspace(0.0,1.0,1000)
samples = [square_func(i) for i in t_samples]
The variable samples
stores a list with the values you need (half of them are '1s' and the other half '-1s', as we are referring to one cycle). The cycle of the function produced with this code is shown in the following figure:
Upvotes: 2
Reputation: 47
I ended up answering it in this way
F=zeros(1000)
F[0:500]=1
F[500:1000]=-1
Upvotes: 0
Reputation: 18022
The function can be defined this way.
def f(t):
return 1 if int(2 * t) % 2 == 0 else -1
And if you are using python 2.x you can use map to create the list.
N = 1000
sample = map(f, xrange(N)) # Or alternatively map(lambda n: f(n), xrange(N))
Upvotes: 1
Reputation: 4280
Let's assume you have a method returning the sample value:
import math
def f(t):
"""
f(t) = 1 if ⌊2t⌋ is even, −1 if ⌊2t⌋ is odd
"""
if math.floor(2 * t) % 2 == 0:
return 1
else:
return -1
The easiest way to generate your array would be to do:
a = [f(n) for n in xrange(1000)]
Note: This assumes Python 2.x, use range if Python 3.x
Upvotes: 0