Silverfrost Forums

Welcome to our forums

How to generate input sine signal

24 May 2011 11:47 #8286

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!

25 May 2011 12:39 #8290

is this what you meant ?

!  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
25 May 2011 10:21 #8291

That's exactly what I need! John Campbell, you are great!

25 May 2011 12:50 #8292

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 + wdt) = sin(x)cos(wdt) + cos(x)sin(wdt) cos(x + wdt) = cos(x)cos(wdt) - sin(x)sin(wdt)

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.

      ! 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
Please login to reply.