|
1 | 1 | ---
|
2 | 2 | Title: '.sqrt()'
|
3 |
| -Description: 'Calculates the square root of each element in an array.' |
| 3 | +Description: 'Computes the positive square root of all elements in the input array.' |
4 | 4 | Subjects:
|
5 | 5 | - 'Computer Science'
|
6 | 6 | - 'Data Science'
|
7 | 7 | Tags:
|
8 | 8 | - 'Arrays'
|
9 | 9 | - 'Functions'
|
| 10 | + - 'Math' |
10 | 11 | - 'NumPy'
|
11 | 12 | CatalogContent:
|
12 | 13 | - 'learn-python-3'
|
13 |
| - - 'paths/computer-science' |
| 14 | + - 'paths/data-science' |
14 | 15 | ---
|
15 | 16 |
|
16 |
| -In NumPy, the **`.sqrt()`** method is used to calculate the positive square root of a number or the elements of an array. It is commonly employed in mathematical computations such as solving quadratic equations, applying the Pythagorean Theorem, modelling normal distributions, and more. |
| 17 | +The **`.sqrt()`** function computes the positive square root of all elements in the input array. As a [universal function (ufunc)](https://www.codecademy.com/article/what-are-ufuncs-in-numpy), it operates element-wise and returns an array of the same shape with square root values. |
| 18 | + |
| 19 | +Widely used in fields like statistics, physics, engineering, and machine learning, `.sqrt()` is a powerful tool for performing efficient mathematical operations on numerical arrays of various shapes and data types. |
17 | 20 |
|
18 | 21 | ## Syntax
|
19 | 22 |
|
20 | 23 | ```pseudo
|
21 |
| -numpy.sqrt(array, out=None, where=True) |
| 24 | +numpy.sqrt(x, out=None, where=True, casting='same_kind', order='K', dtype=None) |
22 | 25 | ```
|
23 | 26 |
|
24 |
| -- `array`: A number or array-like structure containing the elements to which the method is to be applied. |
25 |
| -- `out` (Optional): The array where the result is to be stored. If not provided, a new array is created and used for storing the results. |
26 |
| -- `where` (Optional): The condition (array of boolean values) that determines the elements on which the method is to be applied. |
27 |
| - - If the condition is `True` for a particular element, the square root is computed for that element. |
28 |
| - - If the condition is `False` for a particular element, the square root is not computed for that element and the original element is retained. |
29 |
| - - If not provided, the square root is computed for all elements. |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `x`: The input array or scalar value for which to compute the square root. |
| 30 | +- `out` (Optional): The output array where the result will be stored. Must have the same shape as input if provided. |
| 31 | +- `where` (Optional): Boolean array or condition indicating where to calculate the sqrt. By default, it computes the sqrt for all elements (True). |
| 32 | +- `casting` (Optional): Controls what kind of data casting may occur during computation. |
| 33 | +- `order` (Optional): Memory layout of the output array. |
| 34 | +- `dtype` (Optional): Data type of the output array. |
| 35 | + |
| 36 | +**Return value:** |
| 37 | + |
| 38 | +The function returns an array of the same shape as `x`, containing the positive square root of each element in the input array. |
30 | 39 |
|
31 |
| -## Example |
| 40 | +## Example 1: Basic Square Root Calculation |
32 | 41 |
|
33 |
| -The below example shows the `.sqrt()` method in use: |
| 42 | +This example demonstrates how to use NumPy's `.sqrt()` function to calculate the square root of each element in a 1D array: |
34 | 43 |
|
35 | 44 | ```py
|
36 |
| -# Importing the 'numpy' library as 'np' |
37 | 45 | import numpy as np
|
38 | 46 |
|
39 |
| -# Computing the square root of only those elements in the array which is greater than or equal to 5 |
40 |
| -result = np.sqrt([9,-4,25], where=np.array([9,-4,25]) >= 5) |
| 47 | +# Create a 1D array |
| 48 | +array1 = np.array([4, 9, 16, 25]) |
41 | 49 |
|
42 |
| -print(result) |
| 50 | +# Calculate square root of each element |
| 51 | +result = np.sqrt(array1) |
| 52 | + |
| 53 | +# Display the result |
| 54 | +print("Original array:", array1) |
| 55 | +print("Square root result:", result) |
43 | 56 | ```
|
44 | 57 |
|
45 |
| -The output of the above code is shown below: |
| 58 | +The output generated by this code is: |
46 | 59 |
|
47 | 60 | ```shell
|
48 |
| -[3.00000000e+000 6.50227506e-310 5.00000000e+000] |
| 61 | +Original array: [ 4 9 16 25] |
| 62 | +Square root result: [2. 3. 4. 5.] |
49 | 63 | ```
|
50 | 64 |
|
51 |
| -## Codebyte Example |
| 65 | +The `.sqrt()` function processes each element independently, computing the square root and returning a new array with the results. Note that the output array contains floating-point numbers even if the input contains integers. |
52 | 66 |
|
53 |
| -In this codebyte example, the `.sqrt()` method only computes the square root of the elements of the array which are greater than 0: |
| 67 | +## Example 2: Computing Standard Deviation with `.sqrt()` |
54 | 68 |
|
55 |
| -```codebyte/python |
| 69 | +This example shows how to use the `.sqrt()` function in statistical calculations, specifically to compute the [standard deviation](https://www.codecademy.com/resources/docs/numpy/built-in-functions/std) of a dataset: |
| 70 | + |
| 71 | +```py |
56 | 72 | import numpy as np
|
57 | 73 |
|
58 |
| -result = np.sqrt([144,-10,16], where=np.array([144,-10,16]) >= 0) |
| 74 | +# Sample data points |
| 75 | +data = np.array([2, 4, 6, 8]) |
59 | 76 |
|
60 |
| -print(result) |
| 77 | +# Calculate the mean |
| 78 | +mean = np.mean(data) |
| 79 | + |
| 80 | +# Calculate deviations from the mean |
| 81 | +deviations = data - mean |
| 82 | + |
| 83 | +# Square the deviations |
| 84 | +squared_dev = deviations ** 2 |
| 85 | + |
| 86 | +# Calculate the variance (mean of squared deviations) |
| 87 | +variance = np.mean(squared_dev) |
| 88 | + |
| 89 | +# Compute standard deviation using sqrt() |
| 90 | +std_deviation = np.sqrt(variance) |
| 91 | + |
| 92 | +print("Dataset:", data) |
| 93 | +print("Mean:", mean) |
| 94 | +print("Variance:", variance) |
| 95 | +print("Standard Deviation:", std_deviation) |
| 96 | + |
| 97 | +# Compare with NumPy's built-in function |
| 98 | +print("NumPy's std function result:", np.std(data)) |
61 | 99 | ```
|
| 100 | + |
| 101 | +The output of this code is: |
| 102 | + |
| 103 | +```shell |
| 104 | +Dataset: [2 4 6 8] |
| 105 | +Mean: 5.0 |
| 106 | +Variance: 5.0 |
| 107 | +Standard Deviation: 2.236067977499790 |
| 108 | +NumPy's std function result: 2.236067977499790 |
| 109 | +``` |
| 110 | +
|
| 111 | +This example demonstrates how the `.sqrt()` function is used in computing standard deviation, a common statistical measure that indicates how spread out values are from the mean. |
| 112 | +
|
| 113 | +## Codebyte Example: Working with Complex and Negative Numbers |
| 114 | +
|
| 115 | +This code demonstrates how NumPy's `.sqrt()` function operates on 2D arrays, negative values, and with conditional application using the `where` parameter: |
| 116 | +
|
| 117 | +```codebyte/python |
| 118 | +import numpy as np |
| 119 | + |
| 120 | +# Create a 2D array |
| 121 | +array2d = np.array([[1, 4, 9], [16, 25, 36]]) |
| 122 | +print("Original 2D array:") |
| 123 | +print(array2d) |
| 124 | + |
| 125 | +# Calculate square root of each element in the 2D array |
| 126 | +result2d = np.sqrt(array2d) |
| 127 | +print("\nSquare root of 2D array:") |
| 128 | +print(result2d) |
| 129 | + |
| 130 | +# Handle negative values |
| 131 | +neg_array = np.array([-1, -4, -9]) |
| 132 | +complex_result = np.sqrt(neg_array) |
| 133 | +print("\nSquare root of negative values:") |
| 134 | +print(complex_result) |
| 135 | + |
| 136 | +# Use where parameter to calculate sqrt only for values >= 0 |
| 137 | +mixed_array = np.array([-4, 0, 4, 9, -16]) |
| 138 | +filtered_result = np.sqrt(mixed_array, where=mixed_array >= 0) |
| 139 | +print("\nSelective square root calculation:") |
| 140 | +print(filtered_result) |
| 141 | +``` |
| 142 | + |
| 143 | +The example shows that `.sqrt()` works element-wise on 2D arrays, maintaining their shape. For negative numbers, it returns `nan` along with a warning, unless complex handling is specified. The `where` parameter allows selective square root computation based on a condition, such as non-negative values. |
| 144 | + |
| 145 | +## FAQs |
| 146 | + |
| 147 | +<details> |
| 148 | +<summary>1. What happens when I apply `.sqrt()` to negative numbers?</summary> |
| 149 | +<p>By default, NumPy's `.sqrt()` returns `nan` and raises a warning when applied to negative numbers in real-valued arrays. To compute square roots of negative numbers, convert the input to a complex data type.</p> |
| 150 | +</details> |
| 151 | + |
| 152 | +<details> |
| 153 | +<summary>2. Can I use `.sqrt()` with arrays of different data types?</summary> |
| 154 | +<p>Yes, NumPy automatically promotes data types as needed. However, be aware that the return type might differ from the input type, typically returning floating-point numbers.</p> |
| 155 | +</details> |
| 156 | + |
| 157 | +<details> |
| 158 | +<summary>3. What's the difference between [`math.sqrt()`](https://www.codecademy.com/resources/docs/python/math-module/math-sqrt) and `numpy.sqrt()`?</summary> |
| 159 | +<p>`math.sqrt()` works only on scalar values, while `numpy.sqrt()` works on both scalars and arrays, applying the operation element-wise to arrays.</p> |
| 160 | +</details> |
0 commit comments