随机行走计算电阻网络两点之间的等效电阻
配合大模型写的,没优化,正确性也未完全确定,对给的例子是可用的。
import random
import numpy as np
# 定义电阻网络节点和边
graph = {
'A': {'B': 1, 'C': 2},
'B': {'A': 1, 'D': 3},
'C': {'A': 2, 'D': 4},
'D': {'B': 3, 'C': 4}
}
# 构建节点到索引的映射
nodes = sorted(graph.keys())
node_to_index = {node: index for index, node in enumerate(nodes)}
# 构建状态转移矩阵
num_nodes = len(nodes)
transition_matrix = np.zeros((num_nodes, num_nodes))
for node1 in graph:
index1 = node_to_index[node1]
total_conductance = sum(1 / resistance for resistance in graph[node1].values())
for node2, resistance in graph[node1].items():
index2 = node_to_index[node2]
transition_matrix[index1][index2] = (1 / resistance) / total_conductance
# 随机游走函数,记录每条边的经过次数
def random_walk(start_node, end_node, num_walks):
edge_counts = {}
start_index = node_to_index[start_node]
end_index = node_to_index[end_node]
for _ in range(num_walks):
current_index = start_index
while current_index != end_index:
next_index = np.random.choice(num_nodes, p=transition_matrix[current_index])
edge = (nodes[current_index], nodes[next_index])
if edge not in edge_counts:
edge_counts[edge] = 0
edge_counts[edge] += 1
current_index = next_index
return edge_counts
# 计算等效电阻
def calculate_equivalent_resistance(start_node, end_node, num_walks):
edge_counts = random_walk(start_node, end_node, num_walks)
# 构建反向边的计数
reverse_edge_counts = {}
path = {}
for (node1, node2), count in edge_counts.items():
reverse_edge = (node2, node1)
if reverse_edge in edge_counts:
net_count = count - edge_counts[reverse_edge]
if net_count < 0:
net_count = 0
else:
net_count = count
if net_count > 0:
reverse_edge_counts[(node1, node2)] = net_count
path[node1] = node2
# 计算等效电阻
total_voltage = 0
current_node = start_node
while current_node != end_node:
next_node = path[current_node]
resistance = graph[current_node][next_node]
current = reverse_edge_counts[(current_node, next_node)] / num_walks
voltage = current * resistance
total_voltage += voltage
current_node = next_node
return total_voltage
# 计算从 A 到 D 的等效电阻
start_node = 'A'
end_node = 'D'
num_walks = 100000 # 增加游走次数以提高精度
result = calculate_equivalent_resistance(start_node, end_node, num_walks)
print(f"从 {start_node} 到 {end_node} 的等效电阻: {result}")