Search code examples
pythonnetworkxweighted-graph

Why does Networkxs' path_weight function return integer instead of float?


I want to use the function path_weight to calculate the su of weights along a path. The weights are decimals. But the documentation for path_weight says it would return an int. The implementation just sums up the weights along the path, and also works for decimals:

import networkx as nx

G = nx.Graph()

G.add_edge("a", "b", weight=0.6)
G.add_edge("b", "c", weight=0.2)
sum_path_weights = nx.path_weight(G, ["a", "b", "c"], "weight")
print(sum_path_weights) # Output: 0.8

So I am a little alerted to use this function. Does anybody know the deeper reason, why the weights might me decimals but the function wants to return int?


Solution

  • As noted in the comment by @micro5, this can be considered a typo, although the actual reasoning is likely due to the convention of using integers for weights (e.g. a typical example could be that a weight of a link between two nodes is the count of times they exchanged some information).

    There is no explicit type-hinting in the source code, so the code will work with both floats and ints. I submitted PR 5398 to update the docs.