Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to perform arithmetic operation in an array using numpy

Arithmetic Operation in Array using NumPy

Condition for Performing Arithmetic Operations in an Array using NumPy

  • Description:
    NumPy provides efficient ways to perform arithmetic operations on arrays, allowing element-wise operations on large datasets.

    These operations include basic arithmetic like addition, subtraction, multiplication, and division, as well as more advanced operations like squaring, power functions, and trigonometric functions.
Step-by-Step Process
  • Import NumPy:
    Import the NumPy library.
  • Create Arrays:
    Create NumPy arrays using np.array().
  • Perform Basic Arithmetic Operations:
    Addition, Subtraction, Multiplication, and Division between arrays or a scalar.
  • Element-wise Operations:
    Perform element-wise mathematical operations like square, power, or logarithm using NumPy functions.
  • Scalar Operations:
    Apply operations between arrays and scalar values.
Sample Source Code
  • # Code for Arithmetic Operation in Array using NumPy

    import numpy as np

    arr1 = np.array([1, 2, 3, 4, 5])

    arr2 = np.array([6, 7, 8, 9, 10])

    # 1. Addition of two arrays
    add_result = arr1 + arr2
    print("\nAddition of arr1 and arr2:", add_result)

    # 2. Subtraction of two arrays
    sub_result = arr1 - arr2
    print("\nSubtraction of arr1 and arr2:", sub_result)

    # 3. Multiplication of two arrays
    mul_result = arr1 * arr2
    print("\nMultiplication of arr1 and arr2:", mul_result)

    # 4. Division of two arrays
    div_result = arr1 / arr2
    print("\nDivision of arr1 by arr2:", div_result)

    # 5. Scalar addition (Adding 10 to each element of arr1)
    scalar_add = arr1 + 10
    print("\nAddition of 10 to each element of arr1:", scalar_add)

    # 6. Scalar multiplication (Multiplying each element of arr1 by 2)
    scalar_mul = arr1 * 2
    print("\nMultiplication of each element of arr1 by 2:", scalar_mul)

    # 7. Element-wise power (arr1 raised to the power of 2)
    power_result = np.power(arr1, 2)
    print("\nEach element of arr1 raised to the power of 2:", power_result)

    # 8. Element-wise square root (Square root of each element of arr2)
    sqrt_result = np.sqrt(arr2)
    print("\nSquare root of each element in arr2:", sqrt_result)

    # 9. Trigonometric operation (Sine of each element in arr1, assuming radians)
    sin_result = np.sin(arr1)
    print("\nSine of each element in arr1:", sin_result)
Screenshots
  • Arithmetic Operation Output