Java Reference
In-Depth Information
Program 2.5 Newton's approximation algorithm
double a = 2.0 , x, xold ;
x=a;
do {
xold = x;
// compute one iteration
x = (xold+a/xold)/2.0;
System . out . println (x) ;
}
while (Math. abs(x xold) > 1e 10) ;
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899
1.4142135623730949
Netwon's method is provably converging very fast under mild assumptions.
2.4.3 Loop statement: for
Often programmers need to repeat a sequence of instructions by changing some
variables by a given increment step. Although this can be done using the former
while / do structures, Java provides a more convenient structure: the for loop.
The generic syntax of a for structure is as follows:
for(initialCondition; booleanPredicate; update)
{
block_instructions;
}
For example, consider computing the cumulative sum S n of the first n integers:
n− 1
i = n ( n
1)
S n =
.
2
i =0
We have the recurrence equation: S n = n
1+ S n− 1 with S 0 = 0. Therefore to
compute this cumulative sum, we start in reverse from S 0 and get S i by adding
i
1to S i− 1 for all i
∈{
1 , ..., n
}
. Let us use the for structure as follows:
Program 2.6 Cumulative sum
class ForLoop
{ public static void main( String
args [ ] )
int i , n=10;
int cumulLoop=0;
for (i=0;i < n ; i ++)
{ cumulLoop+=i ; }
 
 
Search WWH ::




Custom Search