Function usage

Posted by

JBase-Basic allows the definition of functions, like in any standard programing language.

Benefit is that programs calling functions are much easier to read compared to classic calling of a subroutine.

To do so, name your program “FUNCTION” instead of naming it “SUBROUTINE”.  Of course, you will pass parameter(s) as arguments. From any program you’ll be able to call your function as long as you’ll have declared it at the beginning using “DEFFUN MyFunction()”.

Schematically:

Step 1: create your function

FUNCTION MyFunction(parameter)
(...)
RETURN(returned_result)
END

Step 2: call your function

SUBROUTINE TOTO
DEFFUN MyFunction()
(...)
FORMULA = .... + MyFunction(parameter) * ...
(...)
RETURN
END

Example:

One need to calculate a cumulative Normal distribution of a variable.

      FUNCTION CND(VAR.IN)
$INSERT I_COMMON
$INSERT I_EQUATE
$INSERT I_DX.COMMON
    OUT.PROBA = ''
    
    a1 =  0.31938153
    a2 = -0.356563782
    a3 =  1.781477937
    a4 = -1.821255978
    a5 =  1.330274429
    
    L = ABS(VAR.IN)
    K1 = 1 / (1 + 0.2316419 * L)
    OUT.PROBA = 1 - 1 / SQRT(2 * DX$PI) * EXP(-1*PWR(L,2) / 2) * (a1 * K1 + a2 * PWR(K1,2) + a3 * PWR(K1,3) + a4 * PWR(K1,4) + a5 * PWR(K1,5))
    
    IF VAR.IN < 0 THEN
        OUT.PROBA = 1 - OUT.PROBA
    END
      
    RETURN(OUT.PROBA)
   END

Then in a program needing to use a cumulative Normal distribution (CND) of a variable:

SUBROUTINE xxx
DEFFUN CND()     ; * the cumulative Normal distribution for a variable
(...)
VAR1 = K * EXP(-Rd * Ttm) * CND(d2 * -1) - S0 * EXP(-Rf * Ttm) * CND(d1 * -1)

(...)

RETURN
END

 

 

 

 

 

 

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.