next up previous contents
Next: Scripts Up: Defining functions and procedures Previous: What Functions and Procedures   Contents

An example function

This calculates $\sin (x)/x$ - note the use of if and while.

 
function sinc,x
;+
; This idl function calculates the function sinc(x) = sin(x)/x.
; (  Beware: some authors define sinc(x) = sin(Pi x)/(Pi x)  ) 
; sinc(0)=1, but you cannot calculate this directly as sin(0)/0.
; This routine uses the power series  
; sin(x) / x = 1-(x^2)/3! + (x^4)/5! - (x^6)/7!  for small values of x 
; This function only works for scalars at the moment
; INPUT, x OUTPUT: s
; Written by: Hugh Pumphrey, Edinburgh
;-

if abs(x) gt 0.1 then begin 
    s=sin(x)/x                  ; Use obvious formula if |x| > 0.1  
endif else begin
    j=0
    s=x*0+1.0                   ;make s double if x is double
    term=s                      ;term same type as s

    ;; Calculate power series - stop after 20 terms or if term gets
    ;; very small 
    while j lt 20 and abs(term) gt 1.e-12 do begin
        j=j+2
        term=-1.0*term*x*x/(j*(j+1))
        s=s+term
    endwhile

endelse

return,s

end

IDL> .run sinc
will inform you that it has compiled the function successfully.
IDL> print,sinc(0.05)
    0.999583



lecjm 2008-11-06