Simple Function Graph
<< Temp Converter | LabTrailIndex | GameStateLab >>
Here we can define a simple function
Function.java
public class Function
{
public Function()
{
}
public double of(double x){
return .2*(Math.pow(x,3)+ x*x -17.0*x +15.0);
}
}
And a simple Applet that scales a graph from -10 to 10 in both directions to a 600 x 400 rectangle, with info on the location of the mouse
SimpleFunctionGraph.java
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class SimpleFunctionGraph extends Applet implements MouseMotionListener
{
private Function f;
public static final int WIDTH=600;
public static final int HEIGHT=400;
public static final double X_MIN=-10;
public static final double X_MAX=10;
public static final double Y_MIN=-10;
public static final double Y_MAX=10;
private double xCoord,yCoord;
public void init()
{
f = new Function();
xCoord=0.0;
yCoord=0.0;
this.addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
g.fillRect(0,0,WIDTH, HEIGHT);
g.setColor(Color.BLACK);
int x1=screenX(X_MIN);int y1=screenY(0);
int x2=screenX(X_MAX); int y2=screenY(0);
g.drawLine(x1, y1, x2, y2);
x1=screenX(0);y1=screenY(Y_MIN);
x2=screenX(0);y2=screenY(Y_MAX);
g.drawLine(x1, y1, x2, y2);
g.setColor(Color.RED);
for (double x=X_MIN; x<X_MAX; x+=.1){
// your code here
g.drawLine(x1, y1, x2, y2);
}
g.drawString("x:"+xCoord, 20, 20);
g.drawString("y:"+yCoord, 20, 40);
}
private int screenY(double y) {
double p=(y-Y_MIN)/(Y_MAX-Y_MIN);
return (int)(HEIGHT-p*HEIGHT);
}
private int screenX(double x) {
double p=(x-X_MIN)/(X_MAX-X_MIN);
return (int)(p*WIDTH);
}
@Override
public void mouseDragged(MouseEvent e) { }
@Override
public void mouseMoved(MouseEvent e) {
xCoord= X_MIN+e.getX()*(X_MAX-X_MIN)/(WIDTH);
yCoord= Y_MAX-e.getY()*(Y_MAX-Y_MIN)/(HEIGHT);
repaint();
}
}
See if you can add the for loop to draw the function using a double x and the f.of(x) method.
