Playing with sine waves (iPad)
Posted: Mon Oct 24, 2016 6:34 am
The speed of the SB interpreter keeps amazing me.

Code: Select all
dim v(4096),stat(4)
pi=atan(1)*4 ! time reset
for i=1 to 10
am=3+7*rnd(1) ! fr=3+rnd(50) ! shi=(rnd(1)-2)*pi! vc=0
signal(512,v,am,fr,shi,vc,"+")
next i
' noise(512,v,1,"n","+")
graph(512,v)
button "1" text int(1000*time()) & " msec." at 20,460 size 120,40
end
' sine generator
' N = # of samples
' v() contains (cumulative) generated signal
' ampl = amplitude
' freq = frequency (# of complete cycles)
' shift = phase shift in radians
' vdc = base value for signal
' mode = "+" (add to v()), "0" (init v()), or "-" (subtract from (v))
'
def signal(N,v(),ampl,freq,shift,vdc,mode$)
if mode$<>"+" and mode$<>"0" and mode$<>"-" then return 0
dt=2*freq*.pi/N
for i=0 to N-1
sig=vdc+ampl*sin(i*dt+shift)
if mode$="0" then ! v(i)=sig
else ! if mode$="+" then v(i)+=sig else v(i)-=sig
end if
next i
end def
' random noise generator
' distr$ = Gaussian ("n") or uniform ("u")
' mode$ = add, init, or subtract ("+", "0", or "-")
'
def noise(N,v(),ampl,distr$,mode$)
randomize
if distr$<>"n" and distr$<>"u" then return
if mode$<>"+" and mode$<>"0" and mode$<>"-" then return
for i=0 to N-1
if distr$="u" then ! p=rnd(1)
else ! p=0 ! for j=1 to 12 ! p+=rnd(1) ! next j ! p/=12
end if
p=2*ampl*p-ampl
if mode$="0" then ! v(i)=p
else ! if mode$="+" then v(i)+=p else v(i)-=p
end if
next i
end def
' base statistics of signal
' returns st(4), resp. minimum, maximun, mean, standard deviation
'
def sigstat(N,v(),st())
mini=999999 ! maxi=-999999 ! mean=0 ! st_dev=0
for i=0 to N-1
num=v(i) ! mini=min(mini,num) ! maxi=max(maxi,num) ! mean+=num
next i ! mean/=N
for i=0 to N-1 ! variance+=(v(i)-mean)^2 ! next i
st(0)=mini ! st(1)=maxi ! st(2)=mean ! st(3)=sqrt(variance/(N-1))
end def
def box()
graphics ! graphics clear .8,.8,.8 ! refresh off
get screen size sw,sh ! xc=384 ! yc=224
draw size 3 ! draw color 0,0,0
draw rect 24,24 to 744,424
draw size 1 ! draw alpha .3
for x=24 to 744 step 20 ! draw line x,24 to x,424 ! next x
for y=24 to 424 step 20 ! draw line 24,y to 744,y ! next y
draw size 2 ! draw color 0,0,1 ! draw alpha 1
draw line 24,yc to 744,yc
refresh on
end def
def graph(N,v())
dim stat(4)
sigstat(N,v,stat) ! maxi=stat(1) ! mini=stat(0)
box() ! yc=224 ! draw size 1 ! draw color 1,0,0
if maxi>0 then sc1=200/maxi else sc1=9999
if mini<0 then sc2=-200/mini else sc2=9999
sc=min(sc1,sc2) ! dx=720/N
for i=0 to N-1
if i=0 then draw to 24,yc-sc*v(0) else draw line to 24+i*dx,yc-sc*v(i)
next i
end def
/*
{dsp_util}
' def signal(N,v(),ampl,freq,shift,vdc,mode$)
' def noise(N,v(),ampl,distr$,mode$)
' def sigstat(N,v(),st()) (min, max, mean, st_dev)
' def box()
' def graph(N,v())
ao=12 ! fo=2
for i=1 to 31 step 2 ' Fourrier series for block wave
if i=1 then ! signal(512,v,ao,fo,0,0,"0")
else ! signal(512,v,ao/i,i*fo,0,0,"+")
end if
next i
*/