Lesson 3 Drawing graphs of functions

Points and Activities

  1. How to create a "method".
  2. Type and parameter of method.
  3. method for transforming coordinates

Example 3 Graphs of functions

Screen of the applets

Exm3.java
import java.awt.*;                 
import java.applet.*;              

public class Exm3 extends Applet   
{
    int vxmin,vymin,vxmax,vymax;  //screen coordinates
    double xmin,ymin,xmax,ymax;   //imaginary coordinates
    double dx;                    //interval of x
    
    
    /* initializing */
    public void init(){
        xmin=-5;xmax=5;ymin=-3;ymax=7;
        vxmin=0;vxmax=300;vymin=0;vymax=300;
        dx=0.1;
    }
    
    public void paint(Graphics g){             
        double x1,y1,x2,y2;           
	   
        //back color
        g.setColor(new Color(255, 255, 192)); 
        g.fillRect(vxmin,vymin,vxmax-vxmin,vymax-vymin);
	    
        // xy-coordinates
        g.setColor(Color.black);
        Line(g,0,ymin,0,ymax);
        Line(g,xmin,0,xmax,0);
	    
        //graph
        g.setColor(Color.blue);     
        x2=xmin;y2=func(x2);
        for(x1=xmin;x1<=xmax;x1=x1+dx){
            y1=func(x1);
            Line(g,x1,y1,x2,y2);
            x2=x1;y2=y1;
         }
    }
	
    /* Convert imaginary coordinates to screen cordinates. */
    public int mapX(double x){
        int sx;
        sx= vxmin+(int)((x-xmin)/(xmax-xmin)*(double)(vxmax-vxmin)) ;
        return sx;
    }
    public int mapY(double y){
        int sy;
        sy=vymin+(int)((ymax-y)/(ymax-ymin)*(double)(vymax-vymin));
        return sy;
    }
    
    /* Drawing Line */
    public void Line(Graphics g,double x1,double y1,double x2,double y2){
        g.drawLine(mapX(x1),mapY(y1),mapX(x2),mapY(y2));
    }
    
    /* Defining function */
    public double func(double x){
        double y;
        y=x*x;
        return y;
    }
}


Exm3.html
<HTML>
<HEAD>
<TITLE>Exm3</TITLE>
</HEAD>
<BODY>
<APPLET CODE="Exm3.class" WIDTH=300 HEIGHT=300></APPLET>
</BODY>
</HTML>


Excercise 3a
(1) Modify the applet of example 3, and draw various graphs.
(2) Add a method of drawing the grid of coordinates to the applet of example 3.

Excercise 3b
Add a method of drawing a circle of given radius and given center point to the applet of example 3. Then draw many circles touching x-axis and whose center points are on y=x^2.