static double f(double x) { return Math.sin(x); }This is a very simple Java method - we'll go through it step by step.
static
static
keyword indicates that
this method doesn't depend on anything particular to a given copy
of the class. For now, this can be thought of as a form of optimization.
No matter how many copies of this class exist, only one copy of this
method will, so this saves space. You should get in the habit of
declaring all methods as static
unless you know of a reason
why it shouldn't be. (The compiler will normally tell you if you
can't call a method static
.)
double
double
, which is a double precision
floating point number.
f
double x
x
. Like all other variables, it
has a type - in this case it is also a double. If our method
took more than one argument, they would be listed here separated by
commas, as in f(double x, double y)
return Math.sin(x)
return
keyword signals an exit point for the method.
If the program reaches this point of the code, it calculates the
return value (in this case Math.sin(x)
), exits the method, and
gives the return value to the calling method. Notice that since our method
f
is of type double
, the return value must
also be of type Math.sin
happens to be double
as well, so
we are safe.
So, the method f
isn't all that interesting. It just returns
the value of sin(x). The idea here is that you will be able to change this
method to some other more interesting function of you choosing.
Remember that the formula for Newton's method requires the derivative of the function that we are finding roots for. The next method in our Newton's method code gives us exactly that:
static double fprime(double x) { return Math.cos(x); }This method works just like
f
, except
that it returns the value of cos(x), which is, of course, the derivative
of sin(x). If you change f
, you should
also change fprime
to reflect this change.
5.7 The Main Method |