# NumPy - Find the sum of a 4x4 array containing random values

By IncludeHelp Last updated : December 13, 2023

## Problem statement

Write a Python program to find the sum of a 4x4 array containing random values.

## Prerequisites

To understand the given solution, you should know about the following Python topics:

## Finding the sum of a 4x4 array containing random values

To find the sum of a 4x4 array containing random values, first create a 4x4 array of random values using the numpy.random.rand() method and then use numpy.sum() method that returns the sum of array elements over the given axis.

Below is the syntax of numpy.sum() method:

```numpy.sum(a, axis=None, dtype=None,
out=None, keepdims=<no value>,
initial=<no value>, where=<no value>);
```

Here, a is an array, axis is an optional parameter that specifies the axis value on which we have to find the sum of the elements. Other parameters are also optional.

## Python program to find the sum of a 4x4 array containing random values

Create a 4x4 array with random values and find the sum of its elements with the given axis (0 and 1).

```# Importing numpy module
import numpy as np

# Creating a 4x4 array with random values
arrWithRandomValues = np.random.rand(4, 4)

# Printing the Original array
print("4x4 Array of random values is :\n", arrWithRandomValues)

# Find the sum of elements of a 4x4 array
# containing random values (with axis 0)
result = np.sum(arrWithRandomValues, axis=0)

# Printing the result
print("\nSum of a 4x4 array (with axis = 0 :\n")
print(result)

# Find the sum of elements of a 4x4 array
# containing random values (with axis 1)
result = np.sum(arrWithRandomValues, axis=1)

# Printing the result
print("\nSum of a 4x4 array (with axis = 1 :\n")
print(result)```

## Output

The output of the above program is:

RUN 1:

```4x4 Array of random values is :
[[0.07935551 0.57083471 0.70479514 0.03794456]
[0.4361276  0.58830204 0.51227111 0.39970066]
[0.23199268 0.36474912 0.29289667 0.72410698]
[0.16238231 0.13441153 0.36302774 0.59514854]]

Sum of a 4x4 array (with axis = 0 :

[0.9098581  1.6582974  1.87299067 1.75690074]

Sum of a 4x4 array (with axis = 1 :

[1.39292992 1.93640142 1.61374545 1.25497012]
```

RUN 2:

```4x4 Array of random values is :
[[0.84746384 0.97047842 0.87839761 0.94669672]
[0.07613856 0.6358209  0.85084835 0.15712366]
[0.55398599 0.24202294 0.57245604 0.40953561]
[0.86480264 0.38999863 0.14008646 0.505735  ]]

Sum of a 4x4 array (with axis = 0 :

[2.34239103 2.2383209  2.44178846 2.01909099]

Sum of a 4x4 array (with axis = 1 :

[3.6430366  1.71993146 1.77800059 1.90062273]
```

## Code Explanation

• To use NumPy in the program, we imported the numpy module.
• Create an array of 4x4 dimensions with random values by using the np.random.rand() method and printed the array.
• Then, we used numpy.sum() method to find the sum of its elements over the axes 0 and 1.
• Finally, printed both results on the screen.