theclapp

Search theclapp.blog-city.com

 

Chapter 4, ex 19

posted Wednesday, 15-Jan-2003
23:03 -- Starting 4.19, Java version
23:32 -- done. Spent some time looking for a function to format floats (actually doubles) for printing, but didn't find one quickly enough, so here's the code.
---
// ch04_ex19.java

class ch04_ex19 {
static double[][] create( int rows, int columns, double start, double end ) {
double[][] ar = new double[rows][columns];
double current, step;
int i, j;

for (j = 0, current = start, step = (end - start) / (rows * columns - 1);
j < rows;
j++) {
for (i = 0; i < columns; i++, current += step) {
ar[j][i] = current;
}
}
return( ar );
}

static void print( double[][] ar ) {
int rows = ar.length;
int columns = ar[0].length; // assumes a non-empty square array
int i, j;

for (j = 0; j < rows; j++) {
for (i = 0; i < columns; i++) {
System.out.print( ar[j][i] + " " );
}
System.out.println();
}
}

public static void main(String[] args) {
print( create( 3, 3, 1.0, 10.0 ) );
System.out.println();

print( create( 3, 4, 1.0, 20.0 ) );
System.out.println();

print( create( 5, 5, -10.0, 10.0 ) );
}
}
---

This prints
1.0 2.125 3.25 
4.375 5.5 6.625
7.75 8.875 10.0

1.0 2.7272727272727275 4.454545454545455 6.1818181818181825
7.90909090909091 9.636363636363637 11.363636363636363 13.09090909090909
14.818181818181817 16.545454545454543 18.27272727272727 19.999999999999996

-10.0 -9.166666666666666 -8.333333333333332 -7.499999999999999 -6.666666666666666
-5.833333333333333 -5.0 -4.166666666666667 -3.3333333333333335 -2.5
-1.6666666666666665 -0.8333333333333331 2.220446049250313E-16 0.8333333333333336 1.666666666666667
2.5000000000000004 3.333333333333334 4.166666666666667 5.0 5.833333333333333
6.666666666666666 7.499999999999999 8.333333333333332 9.166666666666666 10.0

... so I know you can see why I wanted a formatter. :)

23:33? -- Started 4.19, Lisp version
00:00 -- Done

---
;;;; chapter 4, ex 19
(defun create (rows columns start end)
(let ((ar (make-array (list rows columns)
:element-type 'double-float
:initial-element 0.0d0))
(current start)
(step (/ (- end start)
(1- (* rows columns)))))
(dotimes (j rows)
(dotimes (i columns)
(setf (aref ar j i) current)
(incf current step)))
ar))

(defun print (ar)
(dotimes (j (array-dimension ar 0))
(dotimes (i (array-dimension ar 1))
(format t "~d " (aref ar j i)))
(format t "~%"))
(format t "~%"))

(print (create 3 3 1d0 10d0))
(print (create 3 4 1d0 20d0))
(print (create 5 5 -10d0 10d0))
---

links: digg this    del.icio.us    technorati    reddit