/Users/lyon/j4p/src/bookExamples/ch26Graphics/draw2d/Vec2d.java

1    package bookExamples.ch26Graphics.draw2d; 
2     
3    class Vec2d { 
4        public double v[] = new double[2]; 
5     
6        public Vec2d(double x, double y) { 
7            v[0] = x; 
8            v[1] = y; 
9        } 
10    
11       public Vec2d(Vec2d u) { 
12           v[0] = u.v[0]; 
13           v[1] = u.v[1]; 
14       } 
15    
16       // methods 
17       public final double dot(Vec2d B) { 
18           return (v[0] * B.v[0] + v[1] * B.v[1]); 
19       } 
20    
21       public final double dot(double Bx, double By) { 
22           return (v[0] * Bx + v[1] * By); 
23       } 
24    
25       public static final double dot(Vec2d A, Vec2d B) { 
26           return (A.v[0] * B.v[0] + A.v[1] * B.v[1]); 
27       } 
28    
29       // forms c = a*this+B 
30       public Vec2d linearComb(double a, Vec2d B) { 
31           return 
32                   new Vec2d( 
33                           a * v[0] + B.v[0], 
34                           a * v[1] + B.v[1]); 
35       } 
36    
37    
38       public final double length() { 
39           return (double) Math.sqrt(v[0] * v[0] + v[1] * v[1]); 
40       } 
41    
42    
43       public final void normalize() { 
44           double t = v[0] * v[0] + v[1] * v[1]; 
45           if (t != 0 && t != 1) t = (double) (1 / Math.sqrt(t)); 
46           v[0] *= t; 
47           v[1] *= t; 
48       } 
49    
50       public String toString() { 
51           return new String("[" + v[0] + ", " + v[1] + "]"); 
52       } 
53    
54       // A = a*A; 
55       public void mult(double factor) { 
56           v[0] = v[0] * factor; 
57           v[1] = v[1] * factor; 
58       } 
59    
60       // A = A + B 
61       public void add(Vec2d B) { 
62           v[0] = v[0] + B.v[0]; 
63           v[1] = v[1] + B.v[1]; 
64       } 
65    
66       // A = A - B 
67       public void sub(Vec2d B) { 
68           //if (B == null) System.out.println("B=null in sub/vec2d"); 
69           v[0] = v[0] - B.v[0]; 
70           v[1] = v[1] - B.v[1]; 
71       } 
72    
73   } 
74