Linear Equation

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.
go to previous page   go to home page   go to next page

Answer:

actual x valueX = x * 599/(2*PI)
0.0 0
2*PI 599

The answers are easy to figure out since multiplication by zero results in zero (at one end) and the (2*PI) in the numerator cancels the (2*PI) in the denominator (at the other end.)

Linear Equation

Since the equation is linear, all the points in between will also be correct. Here is the same thing for the integer Y that is needed to graph the function. Recall that the range of sin(x) (-1 to +1) is to be represented in an applet with a height of 400 pixels. So we need to map (-1 to +1) to (0 to 399).

actual y valueinteger Y to fit applet width
-1.0 399
+1.0 0

Remember that Y=0 for applets corresponds to the very top row and that Y=399 will be the bottom row. Do this by using another linear equation:

Y =  -y * 399/2 + 399/2

Using these two scaling equations, the scheme for drawing the graph is:

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

// The drawing area is 600 by 400.
// (X=0, Y=0) is the top left corner.
//
public class sineWave extends Applet
{

  public void paint ( Graphics gr )
  {
    double inc = 1.0/32.0;

    for ( double x = 0.0; x <= 2*Math.PI; x = x + inc )
    {
      double y     = Math.sin( x );
      double nextx = x + inc;
      double nexty = Math.sin( nextx );

      int startX   = (int)(  x * 599/(2*Math.PI) );
      int startY   = (int)( -y * 399.0/2.0 + 399.0/2.0 );
      int endX     = (int)(  nextx * 599/(2*Math.PI) );
      int endY     = (int)( -nexty * 399.0/2.0 + 399.0/2.0 );

      gr.drawLine( startX, startY, endX, endY );
    }
  }
}

This code is not very pretty, I'll admit. However, it is fairly typical code for computer graphics and many other applications. It is well worth the time you spend with it.

QUESTION 11:

Why do the statements say 399.0/2.0 instead of 399/2 ?