public
class
Newton_Applet5 extends
java.applet.Applet
{
//
Put property data between these lines
//------------------------------------------------
// Data for a ballistic trajectory at a given angle
double tan = Math.tan(Math.PI
/ 4.0);
double cos = Math.cos(Math.PI
/ 4.0);
double g = 9.8; // m/s^2
double v0 = 100; // m/s
//------------------------------------------------
public
void init()
{
// Put code between this
line
//--------------------------------------------------
double
double xl = 0.0;
double
xh = 1.0;
double
step = 1.0;
double
dif = 1.0;
// Constants
double
maxSteps = 50000;
double
tol = 1.0E-2;
int numSteps
= 0;
int numStepsNewton
= 0;
//
First look for the "turn over" of the parabola
while
(f_method(xl)
* f_method(xh)
< 0 )
{
xl += step;
xh += step;
numSteps++;
//
Give up if gone too far
if(
numSteps > maxSteps)
{
System.out.println("No
turn over found");
return;
}
}
//
Now that we are on the "down" side,
// use Newton's method to find the intercept.
xl = xh;
do
{
double
deriv = fp_method(xl);
if(
deriv == 0.0)
{
System.out.println("Derivative
= 0.0");
return;
}
xh = xl - (f_method(xl)/deriv);//
Newton formula
dif = Math.abs(xh-xl);
xl = xh;
numStepsNewton++;
} while
( dif > tol && numStepsNewton < maxSteps);
System.out.println("After
steps ="+numSteps);
System.out.println("
& Newton steps = "+numStepsNewton);
System.out.println("Root
x = "+xm+
"
within tolerance ="+dif);
//--------------------------------------------------
//
and this line.
}
double
f_method(double x)
{
// Put code between this
line
//--------------------------------------------------
double
val = x*tan - (0.5*g*x*x)/(v0*v0*cos*cos); ;
return
val;
//--------------------------------------------------
//
and this line.
}
double
fp_method(double x)
{
// Put code between this
line
//--------------------------------------------------
double
val = tan - (g*x)/(v0*v0*cos*cos); ;
return
val;
//--------------------------------------------------
//
and this line.
}
//
Paint message in Applet window.
public void paint(java.awt.Graphics
g)
{ g.drawString("Newton_Applet5",20,20);
}
//
Can also run this program as an application.
// No windowing needed so just run the applets
// init() function.
public static void main(String
[] args)
{
Newton_Applet5 obj = new Newton_Applet5();
obj.init();
}
}
|