Sin(x) Applet

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:

Because decimal-based floating point numbers have similar problems, but with different numbers. For example 1.0/3.0 == 0.3333... without end. All floating point schemes have similar problems. Since binary has so many other advantages, most computers use it. Electronic calculators sometimes use hardware decimal-based calculations since they always present their results to humans. Also, mainframe computers usually include hardware decimal-based instructions for use in financial calculations.

Sin(x) Applet

(The rest of this chapter may be safely skipped.)

Let us graph the sine of x, for x in the range of 0.0 to 2 PI radians. Here is a start on doing this. The value of PI is part of the class Math. You get it with Math.PI. To get accurate results, let us use an increment of 1 over a power of two. (If you have not read the chapters on applets, you can skip the rest of this chapter with little loss.)

// assume that the drawing area is 600 by 400
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 )
        {
          int startX = (int)x;
          int startY = (int)Math.sin( x );
          int endX   = (int)x + inc;
          int endY   = (int)Math.sin( x+inc );
          gr.drawLine( startX, startY, endX, endY );
        }
    }
}

The idea is that each iteration of the loop will compute two points on the curve sin(x) and connect them with a line. If the separation between all the points is small, all the straight lines will look like a curve. The various floating point values (such as x) are cast into int because that type is what drawLine() expects.

graph of sin x

QUESTION 9:

(Debugging Practice: ) There is a problem with the code as it is so far. Can you find it? Hint: consider the values that sin(x) will have.