Google-Style PageRank Algorithm Simulation

By: fyvo August 2, 2025 Algorithms

Description

This code simulates a simplified PageRank algorithm. It iteratively updates page ranks based on link structure, demonstrating the core concept of Google's influential ranking system.

Code Snippet

import numpy as np

def page_rank(adjacency_matrix, damping_factor=0.85, iterations=100, tolerance=1e-8):
    num_pages = len(adjacency_matrix)
    ranks = np.ones(num_pages) / num_pages  # Initialize ranks equally
    
    for _ in range(iterations):
        new_ranks = (1 - damping_factor) / num_pages + damping_factor * np.dot(adjacency_matrix, ranks)
        if np.linalg.norm(new_ranks - ranks) < tolerance:
            break
        ranks = new_ranks
    return ranks

# Example usage:
# Adjacency matrix representing links between pages (A[i][j] = 1 if page j links to page i)
adjacency_matrix = np.array([
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [1, 0, 0, 1],
    [0, 0, 1, 0]
])

final_ranks = page_rank(adjacency_matrix)
print(f"Final Page Ranks: {final_ranks}")

Discussion (0)