CUDA Networks
vector_subtract_scalar.cu
Go to the documentation of this file.
1 /**
2  * @file vector_subtract_scalar.cu
3  * @brief Implementation of the Vector::subtract_scalar method for GPU-accelerated subtraction of a scalar from a vector.
4  */
5 
6 #include "vector.h"
7 #include <cuda_runtime.h>
8 #include <stdexcept>
9 #include <cfloat>
10 #include <cmath>
11 
12 /**
13  * @brief CUDA kernel for subtracting a scalar from vector elements.
14  * @param data Pointer to the vector data.
15  * @param scalar The scalar to subtract.
16  * @param size Total number of elements in the vector.
17  */
18 __global__ void vectorSubtractScalarKernel(double* data, double scalar, int size) {
19  // Calculate global thread index
20  int idx = blockIdx.x * blockDim.x + threadIdx.x;
21 
22  // Check if thread is within vector bounds
23  if (idx < size) {
24  // Perform subtraction
25  double result = data[idx] - scalar;
26 
27  // Handle underflow
28  if (!isfinite(result)) {
29  result = (result > 0.0) ? DBL_MAX : -DBL_MAX;
30  }
31 
32  // Store the result
33  data[idx] = result;
34  }
35 }
36 
37 /**
38  * @brief Subtracts a scalar value from all elements in the vector.
39  * @param scalar The scalar value to subtract.
40  */
41 void Vector::subtract_scalar(double scalar) {
42  // Calculate total number of elements
43  int size = rows;
44 
45  // Define block and grid dimensions
46  int threadsPerBlock = 256;
47  int blocksPerGrid = (size + threadsPerBlock - 1) / threadsPerBlock;
48 
49  // Launch CUDA kernel
50  vectorSubtractScalarKernel<<<blocksPerGrid, threadsPerBlock>>>(d_data, scalar, size);
51 
52  // Check for kernel launch errors
53  cudaError_t cudaStatus = cudaGetLastError();
54  if (cudaStatus != cudaSuccess) {
55  throw std::runtime_error("Kernel launch failed: " + std::string(cudaGetErrorString(cudaStatus)));
56  }
57 
58  // Synchronize device
59  cudaDeviceSynchronize();
60 }
void subtract_scalar(double scalar)
Subtracts a scalar value from all elements in the vector.
Defines the Vector class for GPU-accelerated vector operations.
__global__ void vectorSubtractScalarKernel(double *data, double scalar, int size)
CUDA kernel for subtracting a scalar from vector elements.