Older Version
Newer Version
tsh73
Jul 31, 2010
this is final code to the Graphics 101 – plotting a function tutorial
nomainwin
global winW, winH, xmin, xmax, ymin, ymax
open "test" for graphics_nsb_nf as #gr
#gr "trapclose [quit]"
#gr "down"
#gr "home"
#gr "posxy w h"
winW=2*w: winH=2*h
'f(x)=1.5*x^2-2*sin(5*x), x in [-2,3]
xmin=-2: xmax=3
nPoints=winW 'we have only this much screen dots in X range
dx=(xmax-xmin)/nPoints 'so this will be step in math coordinates
'now, to get ymin, ymax we have to loop
ymin=f(xmin)
ymax=ymin
for x=xmin to xmax step dx
y=f(x)
if ymin > y then ymin = y
if ymax < y then ymax = y
next
'now we just - plot function. Note same loop
#gr "color red"
#gr "size 3"
y=f(xmin)
#gr "set ";sx(xmin);" ";sy(y) 'just set first dot
for x=xmin to xmax step dx
y=f(x)
#gr "goto ";sx(x);" ";sy(y) 'then connect dots
next
'and finally, add axis
#gr "color black"
#gr "size 1"
#gr "line ";sx(xmin);" ";sy(0);" ";sx(xmax);" ";sy(0)
#gr "line ";sx(0);" ";sy(ymin);" ";sx(0);" ";sy(ymax)
'labeling
#gr "place ";sx(0)+5;" ";sy(0)-5
#gr "\0,0"
#gr "place ";sx(xmax)-20;" ";sy(0)-5
#gr "\X"
#gr "place ";sx(0)+5;" ";sy(ymax)+20
#gr "\Y"
#gr "flush"
#gr, "getbmp drawing 1 1 ";winW;" ";winH
bmpsave "drawing", "graph.bmp"
wait
[quit]
close #gr
end
'"any" function. You can change it as you like
function f(x)
f=1.5*x^2-2*sin(5*x)
end function
'To translate X from interval [a,b] to [c,d] we'll do (X-a)/(b-a)*(d-c)+c.
'create two functions: sx(x) and sy(y)
function sx(x)
sx=(x-xmin)/(xmax-xmin)*winW
end function
function sy(y)
sy=winH-(y-ymin)/(ymax-ymin)*winH 'Y is inverted, so winH-...
end function