001package ch.akuhn.matrix; 002 003/** 004 * A dense vector 005 * 006 * @author Adrian Kuhn 007 */ 008public class DenseVector extends Vector { 009 010 private double unit = 0; 011 /* default */double[] values; 012 013 protected DenseVector(double[] values) { 014 this.values = values; 015 } 016 017 protected DenseVector(int size) { 018 values = new double[size]; 019 } 020 021 /** 022 * Cosine of angle between this and another vector 023 * 024 * @param other 025 * @return the cosine 026 */ 027 public double cosine(DenseVector other) { 028 assert other.size() == this.size(); 029 double sum = 0; 030 for (int n = 0; n < values.length; n++) 031 sum += values[n] * other.values[n]; 032 return sum / (this.norm() * other.norm()); 033 } 034 035 @Override 036 public double get(int index) { 037 return values[index]; 038 } 039 040 @Override 041 public double norm() { 042 if (unit != 0) 043 return unit; // FIXME should purge cache on edit 044 double qsum = 0; 045 for (final double value : values) 046 qsum += value * value; 047 if (qsum == 0) 048 qsum = 1; 049 return unit = Math.sqrt(qsum); 050 } 051 052 @Override 053 public double put(int index, double value) { 054 return values[index] = value; 055 } 056 057 @Override 058 public int size() { 059 return values.length; 060 } 061 062 @Override 063 public Vector times(double scalar) { 064 final double[] times = new double[values.length]; 065 for (int n = 0; n < values.length; n++) 066 times[n] = values[n] * scalar; 067 return new DenseVector(times); 068 } 069 070 @Override 071 public Vector timesEquals(double scalar) { 072 for (int n = 0; n < values.length; n++) 073 values[n] *= scalar; 074 return this; 075 } 076 077 @Override 078 public boolean equals(Vector v, double epsilon) { 079 if (size() != v.size()) 080 return false; 081 assert v instanceof DenseVector; 082 final DenseVector d = (DenseVector) v; 083 for (int i = 0; i < values.length; i++) { 084 if ((values[i] - d.values[i]) > epsilon) 085 return false; 086 } 087 return true; 088 } 089 090 @Override 091 public double[] unwrap() { 092 return values; 093 } 094 095}