gpt-4.1-mini-2025-04-14· OpenAI
LMArena Human Preference 140K
Give me a Python function that performs the dot product
- User
Give me a Python function that performs the dot product
- Assistant
Certainly! Here's a simple Python function that computes the dot product of two vectors (lists or tuples of numbers):
def dot_product(vec1, vec2): """ Calculate the dot product of two vectors. Args: vec1 (list or tuple of numbers): First vector. vec2 (list or tuple of numbers): Second vector. Returns: float: The dot product of vec1 and vec2. Raises: ValueError: If the vectors are not the same length. """ if len(vec1) != len(vec2): raise ValueError("Vectors must be the same length") return sum(x * y for x, y in zip(vec1, vec2))Example usage:
v1 = [1, 2, 3] v2 = [4, 5, 6] result = dot_product(v1, v2) print(result) # Output: 32This function multiplies corresponding elements of the two vectors and sums the results, which is the definition of the dot product.
- User
Do the same for C++
- Assistant
Certainly! Here's a simple C++ function that computes the dot product of two vectors using
std::vector:#include <iostream> #include <vector> #include <stdexcept> // For std::invalid_argument double dotProduct(const std::vector<double>& vec1, const std::vector<double>& vec2) { if (vec1.size() != vec2.size()) { throw std::invalid_argument("Vectors must be the same length"); } double result = 0.0; for (size_t i = 0; i < vec1.size(); ++i) { result += vec1[i] * vec2[i]; } return result; } int main() { std::vector<double> v1 = {1.0, 2.0, 3.0}; std::vector<double> v2 = {4.0, 5.0, 6.0}; try { double result = dotProduct(v1, v2); std::cout << "Dot product: " << result << std::endl; // Output: 32 } catch (const std::invalid_argument& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }Explanation:
- The function
dotProducttakes twostd::vector<double>arguments. - It checks if the vectors have the same size and throws an exception if not.
- It calculates the sum of the products of corresponding elements.
- The
mainfunction demonstrates usage and handles potential exceptions.
Let me know if you want a version using raw arrays or templates!
- The function
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.