|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +// DAXPY: Constant times a vector plus a vector |
| 5 | +// y = alpha * x + y |
| 6 | +// x: vector of length N with stride incx |
| 7 | +// y: vector of length N with stride incy (modified in place) |
| 8 | +// alpha: scaling factor |
| 9 | +void daxpy(int N, double alpha, const double* x, int incx, double* y, int incy) { |
| 10 | + for (int i = 0; i < N; i++) { |
| 11 | + y[i * incy] += alpha * x[i * incx]; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +// Simple version (stride = 1) |
| 16 | +void simple_daxpy(int N, double alpha, const double* x, double* y) { |
| 17 | + for (int i = 0; i < N; i++) { |
| 18 | + y[i] += alpha * x[i]; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +// Single precision version |
| 23 | +void saxpy(int N, float alpha, const float* x, int incx, float* y, int incy) { |
| 24 | + for (int i = 0; i < N; i++) { |
| 25 | + y[i * incy] += alpha * x[i * incx]; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +void print_vector(const double* x, int N, const char* name) { |
| 30 | + printf("%s: [", name); |
| 31 | + for (int i = 0; i < N; i++) { |
| 32 | + printf("%.2f", x[i]); |
| 33 | + if (i < N - 1) printf(", "); |
| 34 | + } |
| 35 | + printf("]\n"); |
| 36 | +} |
| 37 | + |
| 38 | +int main() { |
| 39 | + const int N = 5; |
| 40 | + const double alpha = 2.0; |
| 41 | + |
| 42 | + double x[] = {1.0, 2.0, 3.0, 4.0, 5.0}; |
| 43 | + double y[] = {10.0, 20.0, 30.0, 40.0, 50.0}; |
| 44 | + |
| 45 | + printf("AXPY Test: y = alpha * x + y\n"); |
| 46 | + printf("alpha = %.2f\n", alpha); |
| 47 | + print_vector(x, N, "x"); |
| 48 | + print_vector(y, N, "y (before)"); |
| 49 | + |
| 50 | + // Apply axpy |
| 51 | + simple_daxpy(N, alpha, x, y); |
| 52 | + |
| 53 | + print_vector(y, N, "y (after)"); |
| 54 | + |
| 55 | + printf("\nManual verification:\n"); |
| 56 | + printf("y[0] = 2.0*1.0 + 10.0 = 12.00\n"); |
| 57 | + printf("y[1] = 2.0*2.0 + 20.0 = 24.00\n"); |
| 58 | + printf("y[2] = 2.0*3.0 + 30.0 = 36.00\n"); |
| 59 | + printf("y[3] = 2.0*4.0 + 40.0 = 48.00\n"); |
| 60 | + printf("y[4] = 2.0*5.0 + 50.0 = 60.00\n"); |
| 61 | + |
| 62 | + // Test with stride |
| 63 | + printf("\n\nTesting with stride=2:\n"); |
| 64 | + double x2[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}; |
| 65 | + double y2[] = {100.0, 200.0, 300.0, 400.0, 500.0, 600.0}; |
| 66 | + |
| 67 | + printf("x: [1, 2, 3, 4, 5, 6]\n"); |
| 68 | + printf("y (before): [100, 200, 300, 400, 500, 600]\n"); |
| 69 | + printf("Computing: y[::2] += 10.0 * x[::2]\n"); |
| 70 | + |
| 71 | + daxpy(3, 10.0, x2, 2, y2, 2); // y[0,2,4] += 10*x[0,2,4] |
| 72 | + |
| 73 | + printf("y (after): [%.1f, %.1f, %.1f, %.1f, %.1f, %.1f]\n", |
| 74 | + y2[0], y2[1], y2[2], y2[3], y2[4], y2[5]); |
| 75 | + printf("Expected: [110.0, 200.0, 330.0, 400.0, 550.0, 600.0]\n"); |
| 76 | + |
| 77 | + return 0; |
| 78 | +} |
0 commit comments