Showing posts with label grid generation. Show all posts
Showing posts with label grid generation. Show all posts

Friday, August 16, 2024

Real-Life Example of Using numpy.fromfunction to Calculate Euclidean Distance from the Origin



### Example: Calculating the Euclidean Distance from the Origin

Suppose you want to create a 2D grid where each element represents the Euclidean distance of that point from the origin `(0, 0)`.

#### Steps:
1. **Define the function** that calculates the Euclidean distance from the origin.
2. **Use `numpy.fromfunction`** to apply this function across a 2D grid.

#### Code Example:


import numpy as np

# Define a function that calculates the Euclidean distance from the origin
def euclidean_distance(x, y):
    return np.sqrt(x**2 + y**2)

# Create a 5x5 grid using fromfunction, where each value is the distance from (0, 0)
distance_grid = np.fromfunction(euclidean_distance, (5, 5))

print(distance_grid)


#### Output:


[[0. 1. 2. 3. 4. ]
 [1. 1.41421356 2.23606798 3.16227766 4.12310563]
 [2. 2.23606798 2.82842712 3.60555128 4.47213595]
 [3. 3.16227766 3.60555128 4.24264069 5. ]
 [4. 4.12310563 4.47213595 5. 5.65685425]]


### Explanation:

- **The Function `euclidean_distance(x, y)`**: 
  - This function computes the distance of any point `(x, y)` from the origin `(0, 0)` using the formula:  
    `distance = sqrt(x^2 + y^2)`
  
- **The Array**:
  - The grid generated by `np.fromfunction(euclidean_distance, (5, 5))` is a 5x5 matrix.
  - Each element in this matrix is the distance of that point `(x, y)` from the origin `(0, 0)`.

### Real-Life Applications:

1. **Geography:**
   - **Distance Maps:** This approach can be used to create distance maps, like calculating the distance from a city center or a landmark across a grid representing a geographical area.
  
2. **Physics:**
   - **Field Calculations:** In physics, such grids can be used to calculate the potential or intensity at various points in a field, for example, calculating electric or gravitational potential.
  
3. **Computer Graphics:**
   - **Gradient Effects:** In computer graphics, distance fields can be used to create gradient effects, soft shadows, or even anti-aliasing in text rendering.

This example demonstrates how `numpy.fromfunction` can be leveraged to generate arrays based on spatial or mathematical relationships, which is valuable in various scientific and engineering applications.

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts