public class Vector { /* Compute alpha*x + y and store in dest (daxpy-like operation) * * Arguments: * dest - destination vector. Can be the same as x or y. * alpha - scalar multiplier * x, y - vector inputs * n - vector size */ public static void axpy(double [1d] dest, double alpha, double [1d] x, double [1d] y) { foreach (i in dest.domain()) dest[i] = alpha*x[i] + y[i]; } /* Compute the dot product of two vectors x'*y * * Arguments: * x, y - vector inputs * n - vector size */ public static double dot(double [1d] x, double [1d] y) { int i; double sum = 0; foreach (i in x.domain()) sum += x[i]*y[i]; return sum; } public static String toString(double [1d] v) { String result = "["; int low = v.domain().min()[1]; int high = v.domain().max()[1]; for (int i = low; i < high; i++) { result += v[i] + ", "; } return result + v[high] + "]"; } public static String toString(int [1d] v) { String result = "["; int low = v.domain().min()[1]; int high = v.domain().max()[1]; for (int i = low; i < high; i++) { result += v[i] + ", "; } return result + v[high] + "]"; } /* Local addScan */ public static int [1d] addScan (int [1d] v) { int [1d] sums = new int [v.domain()]; Point <1> min = v.domain().min(); if (v.domain().size() == 0) return sums; sums[min] = v[min]; for (int i = min[1]+1; i <= v.domain().max()[1]; i++) { sums[i] = sums[i-1] + v[i]; } return sums; } public static void tester (String [] args) { int n = 10; int [1d] vi1 = new int [0:n]; int [1d] vi2 = new int [0:n]; int [1d] vi3 = new int [0:n]; vi1.set(2); foreach (p in vi2.domain()) { vi2[p] = p[1]; } double [1d] vd1 = new double [0:n]; double [1d] vd2 = new double [0:n]; double [1d] vd3 = new double [0:n]; vd1.set(2); foreach (p in vd2.domain()) { vd2[p] = p[1]; } System.out.println("vi1 = " + toString(vi1)); System.out.println("vi2 = " + toString(vi2)); System.out.println("addScan(vi1) = " + toString(addScan(vi1))); System.out.println("addScan(vi2) = " + toString(addScan(vi2))); System.out.println("vd1 = " + toString(vd1)); System.out.println("vd2 = " + toString(vd2)); System.out.println("dot(vd1,vd2) = " + dot(vd1,vd2)); axpy(vd3,3,vd1,vd2); System.out.println("axpy(vd3,3,vd1,vd2) = " + toString(vd3)); } }