Skip to content
Rebecca G. Bettencourt edited this page Aug 28, 2014 · 1 revision

Grapher

Sample code to graph mathematical functions.

#!/usr/bin/xion

on graph y as string is "sqrt(x)", leftWindow as number is -10, rightWindow as number is 10, ¬
        topWindow as number is 5, bottomWindow as number is -5, ¬
        columnsAvailable as integer is 80, rowsAvailable as integer is 20
    local theGraph as string is empty
    
    repeat with j = 1 to rowsAvailable
        put rpad("",columnsAvailable) into line j of theGraph
        
        put round( 1 + (0-leftWindow) * columnsAvailable / (rightWindow-leftWindow) ) into i
        if not (i < 1 or i > columnsAvailable or (not (i=i))) then
            put "|" into char i of line j of theGraph
        end if
    end repeat
    
    put round( 1 + (0-topWindow) * rowsAvailable / (bottomWindow-topWindow) ) into j
    if not (j < 1 or j > rowsAvailable or (not (j=j))) then
        put rpad("",columnsAvailable,"-") into line j of theGraph
    end if
    
    repeat with i = 1 to columnsAvailable
        put leftWindow + (i-1) * (rightWindow-leftWindow) / (columnsAvailable-1) into xx
        
        put xx into x
        put the value of y into yy
        
        put round( 1 + (yy-topWindow) * rowsAvailable / (bottomWindow-topWindow) ) into j
        if j < 1 or j > rowsAvailable or (not (j=j)) then next repeat
        else put "*" into char i of line j of theGraph
    end repeat
    
    if theGraph ends with the lineEnding then delete char -(the length of the lineEnding) to -1 of theGraph
    put theGraph
end graph

repeat
    ask "Enter an equation in terms of x to graph:"
    if it is empty or the result is "Cancel" then exit repeat
    graph it
end repeat
Clone this wiki locally