View previous topic :: View next topic |
Author |
Message |
Srabon
Joined: 22 Feb 2011 Posts: 14
|
Posted: Tue May 24, 2011 12:47 pm Post subject: How to generate input sine signal |
|
|
Hello,
Could anybody help me with
1. writing fortran codes to generate input sine signal
2. getting the values of the created signal in a text file with sample length of 10k?
The parameters for the sine signal are,
u(t) = v+ASinwt
v=1
A=15
w=125
deltat=0.0001
Thank you for kind suggestion! |
|
Back to top |
|
 |
JohnCampbell
Joined: 16 Feb 2006 Posts: 2615 Location: Sydney
|
Posted: Wed May 25, 2011 1:39 am Post subject: |
|
|
is this what you meant ?
Code: | ! Print u(t) = v+ASinwt for 10k values to a text file, one per line
!
real*8 v, A, w, t, deltat, u
integer*4 i
!
v = 1
A = 15
w = 125 ! is that 125 radians per second ?
deltat = .0001 ! is that 0.1 milliseconds ?
!
open (unit=11, file='v_plus_ASinwt.log')
do i = 0,10000
t = dble(i) * deltat
u = v + A*sin(w*t)
write (11,fmt='(f0.6)') u
end do
end |
|
|
Back to top |
|
 |
Srabon
Joined: 22 Feb 2011 Posts: 14
|
Posted: Wed May 25, 2011 11:21 am Post subject: |
|
|
That's exactly what I need!
John Campbell, you are great! |
|
Back to top |
|
 |
davidb
Joined: 17 Jul 2009 Posts: 560 Location: UK
|
Posted: Wed May 25, 2011 1:50 pm Post subject: |
|
|
This is one of those times when the Trigonometry you learned in school can help. Remember those formula for calculating the SINs and COSines of additions (No??). Well, using them you can write:
sin(x + w*dt) = sin(x)*cos(w*dt) + cos(x)*sin(w*dt)
cos(x + w*dt) = cos(x)*cos(w*dt) - sin(x)*sin(w*dt)
This means that given the sine and cosine at x you can calculate them at x+w*dt, and therefore can use iteration to setup all of the values for the sine wave without using SIN (as a bonus you get the cosine wave as well but you can just discard it).
Using these we can refactor John's code so that there is no need to calculate any SINs inside the loop. Just one SIN and one COS calculation will do! (see below).
This could matter if you want efficient code. Good look.
Code: |
! Get sin and cos of w*deltat outside the loop.
cos_wdt = cos(w*deltat)
sin_wdt = sin(w*deltat)
! Initial values.
my_sin = 0.0 ! Initial SIN is 0
my_cos = 1.0 ! Initial COS is 1
! Write first value to file
u = v + A*my_sin
write (11,fmt='(f0.6)') u
! Loop starts at 1 now
do i = 1,10000
! Update cos and sin of "angle" using trigonometry formulae
! Note the sin is stored in a temporary first so it isn't overwritten
! for the cosine calculation.
my_sin1 = my_sin*cos_wdt + my_cos*sin_wdt
my_cos = my_cos*cos_wdt - my_sin*sin_wdt
my_sin = my_sin1
! Calculate the value and write it to the file
u = v + A*my_sin
write (11,fmt='(f0.6)') u
end do
|
|
|
Back to top |
|
 |
|